Search code examples
javascriptarraysjsondynamodb-queries

javascript map function for objects multi level


How can I loop through all the entries in an array using JavaScript? , javascript map function for objects multi level

Example

const  myObject = [
  {
    'name' : {'s': 'name1'},
    'surname' : {'s': 'surname1'},
    'tel' : {'n': 2223456789}
  },
  {
    'name' : {'s': 'name2'},
    'surname' : {'s': 'surname2'},
    'tel' : {'n': 1234567890}
  }
]

Result


const newObject = [
  {
  'name' :'name1',
  'surname' : 'surname1',
  'tel' : 2223456789
  },
  {
  'name' : 'name2',
  'surname' : 'surname2',
  'tel' :  1234567890
  }
]

Solution

  • const myObject = [
        {
            'name': { 's': 'name1' },
            'surname': { 's': 'surname1' },
            'tel': { 'n': 2223456789 }
        },
        {
            'name': { 's': 'name2' },
            'surname': { 's': 'surname2' },
            'tel': { 'n': 1234567890 }
        }
    ]
    
    const newObj = myObject.map(mo => {
        const o = {};
        for (const k in mo) {
            o[k] = mo[k][Object.keys(mo[k])[0]];
        }
        return o;
    })
    
    console.log(newObj);