Search code examples
javascriptnpmlodash

Transform object by removing a property but maintaining its content


I'm trying to find a method to "reduce" an object. This is what i have

{ _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' } }
    ] 
}

and this is what i'd like to have

{  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' } 
    ] 
}

Basically removing the _attributes property, but maintaining its content. I'd like to know if is there some smart method other than looping the object.


Solution

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