I have an array of objects like so
我有一个这样的对象数组
obj = [
{
id: 3,
data: foo
},
{
id: 7,
data: bar
}
]
but I need to get it to
但我得把它弄好
obj = {
3: {
id: 3,
data: foo
},
7: {
data: bar
}
}
having the id in the sub object is not needed but might be handy. What would be the best way to achieve this? I am not sure if there is a simple way to extract a property as an index?
在子对象中拥有id是不需要的,但可能很方便。达到这一目标的最佳方式是什么?我不确定是否有一个简单的方法来提取一个属性作为索引?
Thanks for any help!
感谢任何帮助!
2 个解决方案
#1
2
obj2 = {};
obj.forEach(function(x){
obj2[x.id] = x;
});
#2
0
Anytime you're working with object manipulation you should consider using the Underscore JavaScript library. It really makes working with them much easier and will deal with browser incompatibilities for you. Specifically here I would use the map
function:
在处理对象操作时,应该考虑使用下划线JavaScript库。它确实使与它们一起工作变得更加容易,并将为您处理浏览器的不兼容性。这里我将使用map函数:
var newObj = _.map(obj, function (subobj) {
var tempObj = {};
tempObj[subobj.id] = subobj;
return tempObj;
});
#1
2
obj2 = {};
obj.forEach(function(x){
obj2[x.id] = x;
});
#2
0
Anytime you're working with object manipulation you should consider using the Underscore JavaScript library. It really makes working with them much easier and will deal with browser incompatibilities for you. Specifically here I would use the map
function:
在处理对象操作时,应该考虑使用下划线JavaScript库。它确实使与它们一起工作变得更加容易,并将为您处理浏览器的不兼容性。这里我将使用map函数:
var newObj = _.map(obj, function (subobj) {
var tempObj = {};
tempObj[subobj.id] = subobj;
return tempObj;
});