尝试使用嵌套在子对象结构中的值映射对象数组:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "batchoperations.s3.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]}
结构如下:
const objs = [{
"B": {
"value": 1,
},
"D": {
"value": "45"
},
"E": {
"value": "234"
},
"A": {
"value": "543"
},
"C": {
"value": "250"
}
},...]
,映射结果为[
{ name: 'B', value: 1 },
{ name: 'D', value: '45' },
{ name: 'E', value: '234' },
{ name: 'A', value: '543' },
{ name: 'C', value: '250' }
]
undefined
示例:Stackblitz
答案 0 :(得分:3)
return
在Object.keys
中丢失。同样,也可以使用Object.keys
代替Object.entries
来获取key
和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);
答案 1 :(得分:3)
您缺少return
语句和value
属性定义。
此外,您可能希望使用flatMap而不是map以避免结果中出现嵌套数组:
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)
答案 2 :(得分:2)
您应该对objs [0]而不是objs进行操作,因为它是一个对象的数组,而不是对象的数组。
let array = []
for(let object in objs[0]){
array.push({
"name": object,
"value": objs[0][object].value
})
}