Luis Febro
Luis Febro

Reputation: 1850

JS: put all obj's keys together as each new element in an array

const dataArray = [
    { keyA: ["valueA1", "valueA2"] },
    { keyB: ["valueB1", "valueB2"] },
    { keyC: ["valueC1", "valueC2"] },
]

Put all obj's keys together as each new element and match inner array's elements with their respective index order.

The inner array's values are always fetched in the same index's order.

the following intended result explains better what I mean:

[
    {
        keyA: "valueA1",
        keyB: "valueB1",
        keyC: "valueC1",
    },
    {
        keyA: "valueA2",
        keyB: "valueB2",
        keyC: "valueC2",
    }
]

Upvotes: 0

Views: 29

Answers (1)

Heet Vakharia
Heet Vakharia

Reputation: 445

You can do something like this

const dataArray = [{
    keyA: ['valueA1', 'valueA2']
  },
  {
    keyB: ['valueB1', 'valueB2']
  },
  {
    keyC: ['valueC1', 'valueC2']
  },
];
const keys = dataArray.map((data) => Object.keys(data)[0]);
const result = [];

let keyIndex = 0;
let valueIndex = 0;

while (valueIndex < dataArray[0].keyA.length) {
  const obj = {};
  for (keyIndex = 0; keyIndex < keys.length; keyIndex++) {
    obj[keys[keyIndex]] = dataArray[keyIndex][keys[keyIndex]][valueIndex];
  }

  result.push(obj);
  valueIndex++;
}
console.log(result);

Upvotes: 2

Related Questions