我有一个JavaScript数组,格式如下:
[{key: '123', data: ['a', 'b', 'c']}, {key:'234', data: ['b', 'c', 'd']}];
预期结果:
[{a: '123'}, {b:['123', '234'}, {c:['123', '234']}, {d:['234']}]
我尝试了groupBy
,map
,reduce
以及其他几个lodash函数,但没有任何回报接近我需要的内容。
答案 0 :(得分:0)
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"]}]