我现在看起来像这样的JSON
{
"_id": "5371f7171b27d11418bd9b46",
"name": "a",
"length": 14
},
{
"_id": "5371f7171b27d1143bd9b46",
"name": "ab",
"length": 3
}
我试图让它看起来像这个,
5371f7171b27d11418bd9b46: {
name: "a",
length: 14,
toc: [] // in the future it will be in the json I get.
},
5371f7171b27d1143bd9b46: {
name: "ab",
length: 3,
toc: []
}
这就是我试过的,
var arrenged = {};
_.forEach(result, function(item) {
arrenged[item._id] = arrenged[item._id] || {};
arrenged[item._id][item.name] = arrenged[item._id][item.name] || {};
arrenged[item._id][item.name].push(item);
arrenged[item._id]['direction'] = 'rtl';
arrenged[item._id]['toc'] = "[]";
});
res.jsonp(arrenged);
但我得到TypeError:对象#没有方法'推送',不确定我做错了什么。 谢谢!
答案 0 :(得分:2)
可以这样做:
var newObject = {};
for (var i = 0; i < data.length; i++) { //data is your current array of objects
var id = data[i]._id;
newObject[id] = {};
newObject[id].name = data[i].name;
newObject[id].length = data[i].length;
newObject[id].toc = [];
}