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?
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)
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.