skip to Main Content

Given the following structure I’m trying to remove and flatten the array of objects to be the same as the objectArrayResult below.

const objectArray = [
   {
      "dynamicID1": {
         'key1': 'value1'
      },
      "dynamicID2": {
          'key2': 'value2'
      },
   }
]

The result should be:

const objectArrayResult = [
    {
        'key1': 'value1'
    },
    {
        'key2': 'value2'
    }
]

2

Answers


  1. First, you need to get all the "objects" under "dynamic" fields. Then, for each of these values of dynamic keys, we need to iterate over their props and put it in new object.

    Try this:

    const objectArray = [
       {
          "dynamicID1": {
             'key1': 'value1'
          },
          "dynamicID2": {
              'key2': 'value2'
          },
       }
    ]
    
    const parsed = {}
    
    let keys = Object.values(objectArray[0])
    
    for (let key of keys) {
        for (let prop in key) {
            parsed[prop] = key[prop]
        }
    }
    
    const objectArrayResult = [parsed]
    
    console.log(JSON.stringify(objectArrayResult))

    EDIT

    Here’s one liner suggested in comments:

    const objectArray = [
       {
          "dynamicID1": {
             'key1': 'value1'
          },
          "dynamicID2": {
              'key2': 'value2'
          },
       }
    ]
    
    const objectArrayResult = objectArray.flatMap(x => Object.values(x))
    
    console.log(JSON.stringify(objectArrayResult))
    Login or Signup to reply.
  2. You can use Object.values to get an array of the values of each object, flattening the result with Array#flatMap.

    const objectArray = [
       {
          "dynamicID1": {
             'key1': 'value1'
          },
          "dynamicID2": {
              'key2': 'value2'
          },
       }
    ];
    const res = objectArray.flatMap(Object.values);
    console.log(res);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search