我想做几乎与用户想做的完全相同的事情:Underscore.js: create a map out of list of objects using a key found in the object
...仅
所以,如果我有一个像这样的对象 -
var some_object_array = [{id: 1, val: 55}, {id: 2, val: 1}, {id: 3, val: 45}];
我想将其转换为 -
var some_map = {1: {id: 1, val: 55}, 2: {id: 2, val: 1}, 3: {id: 3, val: 45}};
另外,如果这是一个愚蠢的问题,我道歉。我是JS的新手,我一直试图在过去的两个小时内解决这个问题并继续得到错误的结果。我设法返回一个看起来像这样的对象:
{ '1': [ { id: 1, val: 55 } ],
'2': [ { id: 2, val: 1 } ],
'3': [ { id: 3, val: 45 } ] }
我的代码:
var some_object_array = [ {id: 1, val: 55},
{id: 2, val: 1},
{id: 3, val: 45}
];
function groupBy(array, callback) {
return array.reduce(function (result, item) {
var key = callback(item);
result[key] = item[key] || [];
result[key].push(item);
return result;
}, {});
}
console.log(groupBy(some_object_array, function(i) { return i.id; }));
不太对劲。我的内部对象在数组中,我的键被转换为字符串。不足为奇,但我只是不知道如何修改我的代码。
答案 0 :(得分:0)
你那里的事情太复杂了。
您需要做的只是将项目分配给结果[key]。
var some_object_array = [
{id: 1, val: 55},
{id: 2, val: 1},
{id: 3, val: 45}
];
function groupBy(array, callback) {
return array.reduce(function (result, item) {
var key = callback(item);
result[key] = item;
return result;
}, {});
}
var r = groupBy(some_object_array, function(i) { return i.id; });
console.log(r);
//now lets get item with id 2
console.log(r[2]);
答案 1 :(得分:0)
var objArr = [{id: 1, val: 55}, {id: 2, val: 1}, {id: 3, val: 45}];
var some_map = {1: {id: 1, val: 55}, 2: {id: 2, val: 1}, 3: {id: 3, val: 45}};
// Initialize empty object literal:
let objMap = {};
for (let i = 0; i < objArr.length; i++) {
let key = objArr[i].id;
objMap[key] = objArr[i];
}
console.log('Object Map:\n', objMap);
/* Object Map:
{
"1": {
"id": 1,
"val": 55
}, "2": {
"id": 2,
"val": 1
}, "3": {
"id": 3,
"val": 45
}
}
*/
&#13;