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

我试图找到一种方法来“减少”一个对象。这就是我所拥有的


{ _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属性,但保留其内容。我想知道除了循环对象之外,是否有其他智能方法。


www说
浏览 95回答 2
2回答

隔江千里

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

慕少森

如何做到这一点:reducevar 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);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript