#javascript #javascript-objects
#javascript #javascript-объекты
Вопрос:
Я преобразовал объект javascript из xml, это пример объекта:
{
name: 'current name',
attr1: 'attribute1',
attr2: 'attribute2',
address: {
name: 'name1',
value: {
value: '12'
},
attr3: {
name: 'no name',
attr4: {
attr4: 'attribute4'
}
}
},
price: {
price: '500'
},
in_house: {
in_house: '2'
}
}
как я могу преобразовать в это:
{
name: 'current name',
attr1: 'attr1',
address:{
name: 'name1',
value: '12',
attr3: {
name: 'no name',
attr4: 'attribute3'
}
}
attr2: 'attr2',
price: 500,
in_house: 2
}
необходимо преобразовать весь неиспользуемый объект в свойство, пример
{
Цена :
цена: ‘500’
}
в
{ цена: ‘500’}
Комментарии:
1. Если вы консоль. зарегистрируйте свой объект, вы увидите, что ваш объект недействителен. Я советую вам добавить
,
передprice
2. Спасибо @kevinternet
Ответ №1:
Вы могли бы использовать итеративный, рекурсивный подход к ключам и их значениям.
function moveUp(object, last) {
var keys = Object.keys(object);
if (keys.length === 1 amp;amp; keys[0] in last) {
last[keys[0]] = object[keys[0]];
if (last[keys[0]] !== null amp;amp; typeof last[keys[0]] === 'object') {
moveUp(last[keys[0]], last);
}
return;
}
keys.forEach(function (k) {
if (object[k] !== null amp;amp; typeof object[k] === 'object') {
moveUp(object[k], object)
}
});
}
var object = { name: 'current name', attr1: 'attribute1', attr2: 'attribute2', address: { name: 'name1', value: { value: '12' }, attr3: { name: 'no name', attr4: { attr4: 'attribute4' } } }, price: { price: '500' }, in_house: { in_house: '2' }, test: { test: { test: { banane: 42 } } } };
moveUp(object);
console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Ответ №2:
Вот рекурсивная функция, которая будет перебирать корневой объект и проходить по каждому узлу в нем, чтобы увидеть, есть ли у текущего узла непосредственный дочерний элемент с тем же именем.
const obj = { name: 'current name', attr1: 'attribute1', attr2: 'attribute2',
address: { name: 'name1', value: { value: '12' }, attr3: { name: 'no name', attr4: { attr4: 'attribute4' }}}, price: { price: '500' }, in_house: { in_house: '2' }}
// helper function to check if a value is an object
const isObject = thing => (
typeof thing !== 'undefined' amp;amp;
typeof thing.constructor amp;amp;
thing.constructor === Object
)
const mutateUselessProperties = (root) => {
// we need to recursively go through the root object and return it's result
// after removing properties so we create an inner function for recursion
const go = (obj) => {
// if it's just a value return it
if (!isObject(obj)){
return obj
}
// it's an object so we loop over the keys
for (let key in obj) {
// check if it's an object with a child of the same key
if (isObject(obj[key]) amp;amp; obj[key][key]) {
// reassign the property to it's child of the same name
obj[key] = obj[key][key]
}
// check if it's still an object after possible reassignment
if (isObject(obj[key])) {
// it's an object so recrusively go through the child properties
obj[key] = go(obj[key])
}
// may as well check if we are dealing with an array at the same time
if (Array.isArray(obj[key])) {
obj[key] = obj[key].map(go)
}
}
// return the current iteration
return obj
}
// run the recursive iteration
go(root)
// return the root object that has been mutated
return root
}
console.log(mutateUselessProperties(obj))
Ответ №3:
Если все вложенные отдельные свойства имеют одно и то же имя с родительским свойством, тогда должно работать следующее;
var obj = {
name: 'current name',
attr1: 'attribute1',
attr2: 'attribute2',
address: {
name: 'name1',
value: {
value: '12'
},
attr3: {
name: 'no name',
attr4: {
attr4: 'attribute4'
}
}
},
price: {
price: '500'
},
in_house: {
in_house: '2'
}
};
for (var prop in obj) typeof obj[prop] === "object" amp;amp; Object.keys(obj[prop]).length === 1 amp;amp; (obj[prop] = obj[prop][prop]);
console.log(obj);