我正在尝试将对象的每个属性存储到对象数组中。
例如:
{
a: b,
c: d
}
到
[
{ a: b },
{ c: d }
]
下面是我要执行的代码。
var a = {
a: "a",
b: "b"
}
var newA = []
for (var keys in a) {
if (a.hasOwnProperty(keys)) {
newA.push({
keys: a[keys]
})
}
}
console.log(newA)
当我将属性推送到“newA”数组时,键值被推送为“键”而不是原始键名。
结果:[{keys:a},{keys:b}]
预期:[{a:a},{b:b}]
最佳答案
您需要使用 computed property names .此外,我相信 hasOwnProperty()
在您的代码中是多余的,至少对于这个特定示例而言,您的对象不继承可枚举属性。看for ... in描述。所以你可以去:
for (const key in a)
{
newA.push({[key] : a[key]});
}
但是,您可以使用 Object.entries() 作为替代方案和 Array.map() :
var a = {a : "a", b : "b"};
let res = Object.entries(a).map(([k,v]) => ({[k]: v}));
console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
关于javascript - 对象中的键值未正确填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56482908/