【问题标题】:Transform object by removing a property but maintaining its content通过删除属性但保留其内容来转换对象
【发布时间】:2026-01-21 21:55: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 属性,但保留其内容。 我想知道除了循环对象之外是否有一些聪明的方法。

【问题讨论】:

    标签: javascript npm lodash


    【解决方案1】:

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

    【讨论】:

    • 从技术上讲,这通过整个对象工作,并且有效。我必须明白里面写的一切.....
    • @vitta 这里没什么好理解的,只是spread operator 的陷阱。 :) 而且这种方法不会改变现有对象。
    【解决方案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);

    【讨论】:

    • 谢谢......它就像一个魅力。我正在考虑类似的事情,但我仍然想念一些编写代码的速记方式......