gpt4 book ai didi

javascript - 在数组中添加对象的键值对

转载 作者:行者123 更新时间:2023-11-28 13:23:56 25 4
gpt4 key购买 nike

function Person (name, age) {
this.name = name;
this.age = age;
}

var family = []

var people = {alice:40, bob:42, michelle:8, timmy:6};


for (var key in people) {
family.push({key:people[key]})
}

console.log(family);

这并没有给我 key 。它为每个键提供“键”。在数组中添加 {key:value} 对象对的正确方法是什么?

更新基于下面的 K3N 解决方案,我认为如果我们每次都从构造函数中声明,效果最好:

keys = Object.keys(people);
for (var i = 0; i < keys.length; i++) {
family.push(new Person(keys[i], people[keys[i]]));
}

最佳答案

由于您的人员数组包含人名作为键,值作为年龄(要小心,就好像您在时空中出现两个同名的人发生核 react 一样......!)。

你可以这样做:

function Person (name, age) {
this.name = name;
this.age = age;
}

var family = []

var people = {alice:40, bob:42, michelle:8, timmy:6};

var keys = Object.keys(people); // list all (ownProperty) keys in object
for(var i = 0, key; key = keys[i]; i++) { // loop through
family.push(new Person(key, people[key])); // push it
}

document.write(JSON.stringify(family)); // demo output

关于javascript - 在数组中添加对象的键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30827946/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com