skip to Main Content

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.

2

Answers


  1. Here is one solution.

    const input = [
      [{
        prop1: 'FieldName',
        prop2: 'FieldValue'
      }],
    
      [{
        prop1: 'OtherFieldName',
        prop2: 'OtherFieldValue'
      }],
    ]
    
    const output = [];
    for (const arr of input) {
      for (let i = 0; i < arr.length; i++) {
        const item = arr[i];
        output.push({
          id: output.length + 1,
          [item.prop1]: item.prop2
        })
      }
    }
    console.log(output);
    Login or Signup to reply.
  2. 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;
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search