-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.

2
  • @SamiKuhmonen from what he asks, the array flattening seems not the solution. Commented Apr 15, 2023 at 5: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 Commented Apr 15, 2023 at 6:50

2 Answers 2

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;
}

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.