Search code examples
javascriptarraystypescriptobject

How to modify array of object arrays into a single array of objects?


I want to modify existing array which looks like this:

[
 [
  {
   prop1: 'FieldName', 
   prop2: 'FieldValue'
  }
 ],

 [
  {
   prop1: 'OtherFieldName',
   prop2: 'OtherFieldValue'
  }
 ],
]


Into having an array of objects with each object now having an unique id and setting prop1 value as a key for my new object.

[
 {
  id: 1, 
  FieldName: 'FieldValue'
 },
 {
  id: 2, 
  OtherFieldName: 'OtherFieldValue'
 }
]

I know that this probably asks more than the original question, but I think I'm missing something very simple here, just don't know the most optimal way to go about it.


Solution

  • Iterate the original array, create a new object in each iteration, add an .id for it, then iterate the element to get the rest key-value pairs:

    function convert2(arrayOfObjects) {
      const newObjects = [];
      
      for (const [index, keyValuePairs] of arrayOfObjects.entries()) {
        const object = {};
        
        object.id = index + 1;
        
        for (const { prop1: key, prop2: value } of keyValuePairs) {
          object[key] = value;
        }
        
        newObjects.push(object);
      }
      
      return newObjects;
    }
    

    Try it (terser version):

    function convert(arrayOfObjects) {
      return arrayOfObjects.map(
        (keyValuePairs, index) => Object.fromEntries(
          keyValuePairs.map(
            ({ prop1: key, prop2: value }) => [key, value]
          ).concat([
            ['id', index + 1]
          ])
        )
      );
    }
    
    const test = [
      [{ prop1: 'FieldName', prop2: 'FieldValue' }],
      [
        { prop1: 'OtherFieldName', prop2: 'OtherFieldValue' },
        { prop1: 'AnotherFieldName', prop2: 'AnotherFieldValue' }
      ],
    ];
    
    console.log(convert(test));
    .as-console-wrapper {
      max-height: 100% !important;
    }