我正在尝试找到一种“减少”对象的方法。这就是我所拥有的
{ _attributes: { name: 'titolo', description: 'il titolo della sezione' },
field:
[ { _attributes:
{ name: 'titolo',
type: 'input',
label: 'titolo',
value: 'titolo' } },
{ _attributes:
{ name: 'colore',
type: 'input',
select: 'giallo,blu',
label: 'seleziona il colore',
value: 'titolo' } }
]
}
这就是我想要的
{ name: 'titolo', description: 'il titolo della sezione' ,
field:
[
{ name: 'titolo',
type: 'input',
label: 'titolo',
value: 'titolo' } ,
{ name: 'colore',
type: 'input',
select: 'giallo,blu',
label: 'seleziona il colore',
value: 'titolo' }
]
}
基本上删除_attributes属性,但保留其内容。我想知道是否有一些智能方法,而不是循环对象。
let obj = {
_attributes: {
name: 'titolo',
description: 'il titolo della sezione'
},
field: [{
_attributes: {
name: 'titolo',
type: 'input',
label: 'titolo',
value: 'titolo'
}
},
{
_attributes: {
name: 'colore',
type: 'input',
select: 'giallo,blu',
label: 'seleziona il colore',
value: 'titolo'
}
}
]
}
obj = { ...obj._attributes, ...obj };
delete obj._attributes;
obj.field = obj.field.map(el => el._attributes);
console.log(obj);
reduce
: var obj={ _attributes: { name: 'titolo', description: 'il titolo della sezione' }, field: [ { _attributes: { name: 'titolo', type: 'input', label: 'titolo', value: 'titolo' } }, { _attributes: { name: 'colore', type: 'input', select: 'giallo,blu', label: 'seleziona il colore', value: 'titolo' } } ] };
var result = Object.entries(obj).reduce((acc,[k,v])=>{
if(!Array.isArray(v)){
acc = {...v, ...acc};
} else {
field = v.map(({_attributes})=>_attributes);
acc = {...acc, field}
}
return acc;
},{});
console.log(result);