I have a JavaScript object
I'm trying to group these objects by id, and produce a map of a list of names where the key is the id, and the value is the name. Example:
{1 : [John, Jane, Mike], 3: [Bob, Will]}
With the code below, I get:
{1: [John, Jane, Mike, Bob, Will], 3: [John, Jane, Mike, Bob, Will]}
How can I achieve my desired output? Any help would be appreciated.
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);
}
for (i in myObj). Please fix the code and the object to reflect your comments