简体   繁体   English

从令人兴奋的一个节点j建立一个json

[英]re building a json from an exciting one nodejs

I've the current JSON that looks like this 我现在的JSON看起来像这样

      {
        "_id": "5371f7171b27d11418bd9b46",
        "name": "a",
        "length": 14
      },
      {
        "_id": "5371f7171b27d1143bd9b46",
        "name": "ab",
        "length": 3
      }

and I'm trying to get it to look like this one, 我试图让它看起来像这个,

5371f7171b27d11418bd9b46: {
    name: "a",
    length: 14,
    toc: [] // in the future it will be in the json I get.
},
5371f7171b27d1143bd9b46: {
    name: "ab",
    length: 3,
    toc: []
}

this is what I tried, 这是我试过的,

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);

but I get TypeError: Object # has no method 'push', not sure what I'm doing wrong. 但我得到TypeError:对象#没有方法'推',不知道我做错了什么。 thanks! 谢谢!

Could just do: 可以这样做:

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/ 小提琴: http//jsfiddle.net/KWjb3/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM