使用简单的lodash / underscore函数将对象数组从一种形式转换为另一种形式

时间:2015-09-16 19:08:51

标签: underscore.js lodash

我有一个JavaScript数组,格式如下:

[{key: '123', data: ['a', 'b', 'c']}, {key:'234', data: ['b', 'c', 'd']}];

预期结果:

[{a: '123'}, {b:['123', '234'}, {c:['123', '234']}, {d:['234']}]

我尝试了groupBymapreduce以及其他几个lodash函数,但没有任何回报接近我需要的内容。

2 个答案:

答案 0 :(得分:0)

以下代码有效,但我不喜欢使用两个for循环。我相信有更好的方法可以做到这一点。请建议。

var inputArr = [{key:'123',data:['a','b','c']},{key:'234',data:['b','c',' d']}];

var outputArr = [];
var tempObj = {};
angular.forEach(inputArr, function(obj) {
    var key = obj.key;
    angular.forEach(obj.data, function(data) {
        tempObj[data] = {'data': data, 'key': key};
    });
});
outputArr = _.map(tempObj, function(value, index){
  return {'data': index, 'key': value};
});
//[{a: '123'}, {b:['123', '234'}, {c:['123', '234']}, {d:['234']}]

答案 1 :(得分:0)

仅为lulz =):

var t = [{key: '123', data: ['a', 'b', 'c']}, {key:'234', data: ['b', 'c', 'd']}];
var r = {};
var k = _.each(_.uniq([].concat.apply([], _.pluck(t, 'data'))), function(p){
    r[p] = _.pluck(_.filter(t, function(n){return n.data.indexOf(p) > -1}), 'key');
});

console.log(JSON.stringify(r));

结果(作为对象):

{"a":["123"],"b":["123","234"],"c":["123","234"],"d":["234"]}

var r = [];
var k = _.each(_.uniq([].concat.apply([], _.pluck(t, 'data'))), function(p){
    var q = {};
    q[p] = _.pluck(_.filter(t, function(n){return n.data.indexOf(p) > -1}), 'key');
    r.push(q);
});

结果(作为数组):

[{"a":["123"]},{"b":["123","234"]},{"c":["123","234"]},{"d":["234"]}]