gpt4 book ai didi

javascript - 按 id 对 JavaScript 对象进行分组

转载 作者:行者123 更新时间:2023-12-03 04:58:47 25 4
gpt4 key购买 nike

我有一个 JavaScript 对象

我试图按 id 对这些对象进行分组,并生成一个名称列表的映射,其中键是 id,值是名称。示例:

{1 : [John, Jane, Mike], 3: [Bob, Will]}

通过下面的代码,我得到:

{1: [John, Jane, Mike, Bob, Will], 3: [John, Jane, Mike, Bob, Will]}

如何才能达到我想要的输出?任何帮助将不胜感激。

var myObj = [{
id: 1,
name: "John",
major: "accounting"
},
{
id: 1,
name: "Jane",
major: "accounting"
}, {
id: 1,
name: "Mike",
major: "accounting"
}, {
id: 3,
name: "Bob",
major: "history"
}, {
id: 3,
name: "Will",
major: "history"
}]



for (i in myObj) {
var obj = myObj[i];
var id = obj.id;
var name = obj.name;
var newMap = {};
var namesArray = [];

if (!(id in newMap)) {
namesArray.push(name);
newMap[id] = namesArray;

} else {
for (key in newMap) {
if (key == id) {
namesArray.push(name);
newMap[key] = namesArray;
}
}
}
console.log(newMap);
}

最佳答案

编辑您自己的程序:

var myObj = [{
id: 1,
name: "John",
major: "accounting"
},
{
id: 1,
name: "Jane",
major: "accounting"
}, {
id: 1,
name: "Mike",
major: "accounting"
}, {
id: 3,
name: "Bob",
major: "history"
}, {
id: 3,
name: "Will",
major: "history"
}]


var newMap = {};
var namesArray = [];

for (i in myObj) {
var obj = myObj[i];
var id = obj.id;
var name = obj.name;

if (!(id in newMap)) {
namesArray = [];
namesArray.push(name);
newMap[id] = namesArray;

} else {
namesArray = newMap[id];
namesArray.push(name);

}

}
console.log(newMap);

关于javascript - 按 id 对 JavaScript 对象进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42318700/

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