我有一本看起来像这样的字典:
"Player Details": {
"Sally Smith": {
"player_id": 2,
"color_one": "blue",
"color_two": "red"
},
"John Smith": {
"player_id": 4,
"color_one": "white",
"color_two": "black"
}
}
我需要它进入一个数组并像这样结束:
"Player details": [
{
"player_id": "2",
"color_one": "blue",
"color_two": "red"
},
{
"player_id": "4",
"color_one": "white",
"color_two": "black"
}
]
我尝试了以下方法,但“值”仍然存在:
Object.entries(myDictionary).forEach(([key, value]) => {
newArray.push({value})
});
我觉得我快到了,有人可以帮忙吗?
最佳答案
只需使用 Object.values
从对象中获取值返回数组中的对象属性值的方法。
let data = {
"Player Details": {
"Sally Smith": {
"player_id": 2,
"color_one": "blue",
"color_two": "red"
},
"John Smith": {
"player_id": 4,
"color_one": "white",
"color_two": "black"
}
}
}
let res = {
'Player Details': Object.values(data['Player Details'])
};
// or in case you justt need the array then
let res1 = Object.values(data['Player Details']);
console.log(res)
console.log(res1)
仅供引用:由于您的属性中有空格,您不能使用 dot notation访问属性而不是使用 bracket notation .
关于javascript - 如何从字典中提取项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55540044/