deepak murthy
deepak murthy

Reputation: 411

Convert object of arrays to Array of object with key value pairs

I have an object of arrays

{Cost One: Array(1), Cost Two: Array(1), Cost Five: Array(1)}
    Cost One: Array(1)
    0: "22"
    length: 1

    Cost Two: Array(1)
    0: "33"
    length: 1

    Cost Five: Array(1)
    0: "1456"
    length: 1

Desired output :

[{Cost One: "22"}, {Cost Two: "33"}, {Cost Five: "1456"}]

My code to convert :

const mappedDataArray = [];

for (const key in costsFormValues) {
    const mappedData = {
      ...costsFormValues[key]
    };
mappedDataArray.push(mappedData);
}

Output :

[{…}, {…}, {…}]

0: {0: "22"}
1: {0: "33"}
2: {0: "1456"}

Here instead of 0, how do i add key name that is Cost One and so on

What am i making wrong here ?

Upvotes: 0

Views: 64

Answers (2)

Ashraful Islam
Ashraful Islam

Reputation: 935

let costsFormValues = {
  "Cost One":[22],
  "Cost Two":[33],
  "Cost Three":[1456],
}

let result = Object.keys(costsFormValues).map(key => ({[key]: costsFormValues[key][0].toString()}));
console.log(result);

Upvotes: 0

Shubham Verma
Shubham Verma

Reputation: 5054

You are not setting keys anywhere according to output. It would be something like this:

const costsFormValues = {
  "Cost One":[22],
  "Cost Two":[33],
  "Cost Three":[1456],
}

const mappedDataArray = [];


for (const key in costsFormValues) {
    const mappedData = {
      [key]:costsFormValues[key][0]
    };
mappedDataArray.push(mappedData);
}

console.log(mappedDataArray)

Upvotes: 1

Related Questions