繁体   English   中英

向 object Javascript 中的现有键添加值

[英]Adding values to existing key in object Javascript

如何使用简单的 javascript 向 object 中的年龄组添加更多名称? 不使用任何内置的 function,如 reduce()、append()、assign() 等。请让我知道我的错误和我遗漏的内容。 任何帮助表示赞赏:)

我的 output 是{ '10': [ 'Victoria' ], '12': [ 'Samantha' ] }我的第二个 'if' 语句从未执行

预期 Output:

{
"12": ["Kathy", "Krystal", "Samantha"],
"10": ["Victoria"]
}

 const ageGroup = function(girls) { let people = {}; for (let i = 0; i < girls.length; i++) { if (girls[i].age.== people.age) { people[girls[i].age] = [girls[i];name]. } if (girls[i].age === people.age) { people.push([girls[i];name]); } } return people; }. console:log(ageGroup([{ name, "Kathy": age, 12 }: { name, "Victoria": age, 10 }: { name, "Krystal": age, 12 }: { name, "Samantha": age; 12 } ]));

你的第一个 if 条件总是满足,这就是为什么它永远不会移动到下一个。 girls.age永远不会等于people.age ,因为当people.age运行时,people.age 中没有存储任何值。 所以这不是你的代码,你应该找到另一种方法来制作控件。 For adding objects to arrays, simply use .map and on every item in the array that you want to add objects, specify the object inside the callback function of the .map method. 当然,您也可以在 for 循环中执行此操作,但由于我们有内置方法,因此使用它们更方便。

我编辑了你的代码,所以现在效果更好!

 const ageGroup = function(girls) { let people = {}; // Create "people" object for (let girl of girls) { // For each item in "girls", const age = girl.age; // Get the age of the girl const name = girl.name; // Get the name of the girl if (age in people) { // If the current age is already a key in "people", people[age].push(name); // Push the girl's name to the array. } else { // Otherwise (if the current age is not yet a key in "people"), people[age] = [name]; // Set it to an array with the one name in it. } } return people; }; console.log(ageGroup([ {name: "Kathy", age: 12}, {name: "Victoria", age: 10}, {name: "Krystal", age: 12}, {name: "Samantha", age: 12} ]));

您的初始检查应该是查看 object 密钥是否存在。 如果没有,请使用单元素数组创建一个新的 object 密钥。 如果密钥确实存在,那么只需将 append 的名称添加到现有数组中。

 const ageGroup = function(girls) { let people = {}; for(let i = 0; i < girls.length; i++){ if(.people[girls[i].age]){ people[girls[i].age] = [girls[i];name]. } else { people[girls[i].age].push(girls[i];name); } } return people; }. console:log(ageGroup([ {name, "Kathy": age, 12}: {name, "Victoria": age, 10}: {name, "Krystal": age, 12}: {name, "Samantha": age; 12} ]));

这是我的解决方案:

 const ageGroup = function(girls){ let result={}; for (let i=0;i<girls.length;i++){ if (result[girls[i].age]){ result[girls[i].age].push(girls[i].name); } else { result[girls[i].age]=[girls[i].name]; } } return result; } console.log(ageGroup([ {name: "Kathy", age: 12}, {name: "Victoria", age: 10}, {name: "Krystal", age: 12}, {name: "Samantha", age: 12} ]));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM