Json对象:分组2级属性

时间:2015-12-10 07:47:48

标签: javascript lodash

我有大量的以下类型对象。

[{
    iD: "djfaj",
    compositeAttr: { "type": "book", val: "atlas", domain: "abc.com" },
    otherattr: 'val1'
}, {
    iD: "djfaj1",
    compositeAttr: { "type": "toy", val: "globe", domain: "xyz.com" },
    otherattr: 'val2'
}, {
    iD: "djfaj2",
    compositeAttr: { "type": "toy", val: "car", domain: "xyz.com" },
    otherattr: 'val3'
}
//... some more objects
]

我想要o / p如下:

[{
    "xyz.com": [{
        iD: "djfaj1",
        compositeAttr: { "type": "toy", val: "globe", domain: "xyz.com" },
        otherattr: 'val2'
    }, {
        iD: "djfaj2",
        compositeAttr: { "type": "toy", val: "car", domain: "xyz.com" },
        otherattr: 'val3'
    }]
}, {
    "abc.com": [{
        iD: "djfaj",
        compositeAttr: { "type": "book", val: "atlas", domain: "abc.com" },
        otherattr: 'val1'
    }]
}]

我如何使用lodash或类似的库? 进行此更改将有助于提高性能。

2 个答案:

答案 0 :(得分:2)

只需使用Array.prototype.forEach()进行迭代,然后使用对象进行收集。

var obj = [{ iD: 'djfaj', compositeAttr: { type: 'book', val: 'atlas', domain: 'abc.com' }, otherattr: 'val1' }, { iD: 'djfaj1', compositeAttr: { type: 'toy', val: 'globe', domain: 'xyz.com' }, otherattr: 'val2' }, { iD: ' djfaj2', compositeAttr: { type: 'toy', val: 'car', domain: 'xyz.com' }, otherattr: 'val3' }],
    grouped = {},
    result = [];

obj.forEach(function (a) {
    grouped[a.compositeAttr.domain] = grouped[a.compositeAttr.domain] || [];
    grouped[a.compositeAttr.domain].push(a);
});

Object.keys(grouped).forEach(function (k) {
    var o= {};
    o[k] = grouped[k];
    result.push(o);
});

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

答案 1 :(得分:1)

通过使用lodash你可以尝试这样的东西

 var arr = [{iD: "djfaj", compositeAttr: {"type": "book", val: "atlas", domain: "abc.com"}, otherattr: 'val1'}, {iD: "djfaj1", compositeAttr: {"type": "toy", val: "globe", domain: "xyz.com"}, otherattr: 'val2'}, {iD: "djfaj2", compositeAttr: {"type": "toy", val: "car", domain: "xyz.com"}, otherattr: 'val3'}];

 var result = _(arr).groupBy('compositeAttr.domain').map(function(v, k) {
     var obj = {};
     obj[k] = v;
     return obj;
 }).value();

 console.log(result);

lodash demo link