通过删除属性但保留其内容来变换对象

问题描述 投票:0回答:2

我正在尝试找到一种“减少”对象的方法。这就是我所拥有的

{ _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属性,但保留其内容。我想知道是否有一些智能方法,而不是循环对象。

javascript npm lodash
2个回答
1
投票

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);

0
投票
如何使用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);
© www.soinside.com 2019 - 2024. All rights reserved.