gpt4 book ai didi

javascript - 从令人兴奋的 Nodejs 重新构建 json

转载 作者:行者123 更新时间:2023-12-02 17:24:19 24 4
gpt4 key购买 nike

我当前的 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: Object # has no method 'push',不知道我做错了什么。谢谢!

最佳答案

可以这样做:

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 = [];
}

fiddle :http://jsfiddle.net/KWjb3/

关于javascript - 从令人兴奋的 Nodejs 重新构建 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23631240/

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