-1

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.

  • @SamiKuhmonen from what he asks, the array flattening seems not the solution. – Mario Vernari Apr 15 '23 at 05:10
  • How deeply nested are your arrays? Or just depth of 2? If they are all of know depth then iterative methods quick, otherwise better invoke recursion – Onyambu Apr 15 '23 at 06:50

2 Answers2

0

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);
Mario Vernari
  • 6,649
  • 1
  • 32
  • 44
0

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;
}
InSync
  • 4,851
  • 4
  • 8
  • 30