Trying to map array of objects with values nested in child objects structure like:
const objs = [{
"B": {
"value": 1,
},
"D": {
"value": "45"
},
"E": {
"value": "234"
},
"A": {
"value": "543"
},
"C": {
"value": "250"
}
},...]
to the structure like:
[
{ name: 'B', value: 1 },
{ name: 'D', value: '45' },
{ name: 'E', value: '234' },
{ name: 'A', value: '543' },
{ name: 'C', value: '250' }
]
and the result of the mapping is undefined
const mapped = objs.map((key, index) => {
Object.keys(key).map(el => ({
name: el
}))
})
Example: Stackblitz
You should operate on objs[0], not objs, because it is an array of one object, not array of objects.
let array = []
for(let object in objs[0]){
array.push({
"name": object,
"value": objs[0][object].value
})
}
return
is missing in Object.keys
. As well instead of Object.keys
use Object.entries
to get key
and value
.
const objs = [{ "B": { "value": 1, }, "D": { "value": "45" }, "E": { "value": "234" }, "A": { "value": "543" }, "C": { "value": "250" } }]; const mapped = objs.map((key, _) => { return Object.entries((key)).map(([name, { value }]) => ({ name, value })) }).flat(); console.log(mapped);
You are missing return
statement and value
property definition.
Besides you may want to use flatMap instead of map in order to avoid a nested array in the result:
const objs = [{ "B": { "value": 1, }, "D": { "value": "45" }, "E": { "value": "234" }, "A": { "value": "543" }, "C": { "value": "250" } }] const mapped = objs.flatMap((key, index) => { return Object.keys(key).map(el => ({ name: el, value: key[el].value })) }) console.log(mapped)
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.