0

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 ?

1

2 Answers 2

1

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)

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.