为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

www说 2022-09-29 15:37:01
我试图找到一种方法来“减少”一个对象。这就是我所拥有的{ _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属性,但保留其内容。我想知道除了循环对象之外,是否有其他智能方法。
查看完整描述

2 回答

?
隔江千里

TA贡献1906条经验 获得超10个赞

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


查看完整回答
反对 回复 2022-09-29
?
慕少森

TA贡献2019条经验 获得超9个赞

如何做到这一点: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);


查看完整回答
反对 回复 2022-09-29
  • 2 回答
  • 0 关注
  • 94 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号