我在javascript中有一个JSON对象列表,如下所示:
[{"model":"alpha", "ports":4},
{"model":"beta", "ports":4},
{"model":"beta", "ports":1},
{"model":"beta", "ports":43},
{"model":"gamma", "ports":66},
{"model":"omega", "ports":6},
{"model":"omega", "ports":1}]
现在我需要找出具有相同model
值的所有行,然后在第一个项目中添加include
键,最后生成include
的值key是其余“相同模型”行的列表。
输出应该是这样的:
[{"model":"alpha", "ports":4},
{"model":"beta", "ports":4, "include":[
{"model":"beta", "ports":1},
{"model":"beta", "ports":43}]},
{"model":"gamma", "ports":66},
{"model":"omega", "ports":6, "include":[
{"model":"omega", "ports":1}]}]
任何人都可以给我一个如何实现这个目标的方向吗?
答案 0 :(得分:4)
您可以使用forEach
循环和thisArg
参数
var data = [{"model":"alpha", "ports":4},
{"model":"beta", "ports":4},
{"model":"beta", "ports":1},
{"model":"beta", "ports":43},
{"model":"gamma", "ports":66},
{"model":"omega", "ports":6},
{"model":"omega", "ports":1}];
var result = [];
data.forEach(function(e) {
if(!this[e.model]) {
this[e.model] = e;
result.push(this[e.model]);
} else {
this[e.model].include = (this[e.model].include || []).concat(e);
}
}, {});
console.log(result)
答案 1 :(得分:2)
您可以使用earlier version
var obj =[{"model":"alpha", "ports":4},
{"model":"beta", "ports":4},
{"model":"beta", "ports":1},
{"model":"beta", "ports":43},
{"model":"gamma", "ports":66},
{"model":"omega", "ports":6},
{"model":"omega", "ports":1}];
var res = obj.reduce(function(obj,currentValue){
if (obj.length && obj[obj.length-1].model == currentValue.model){
obj[obj.length-1].include=obj[obj.length-1].include || [];
obj[obj.length-1].include.push(currentValue);
}else{
obj.push(currentValue)
}
return obj;
},[]);
console.log(res);
答案 2 :(得分:0)
function processData(data) {
return data.reduce(function (result, item) {
var first = result.find(function (i) {
return i.model === item.model;
});
if (!first) {
item.include = [];
result.push(item);
} else {
first.include.push(item);
}
return result;
}, []);
}
var data = [{"model":"alpha", "ports":4},
{"model":"beta", "ports":4},
{"model":"beta", "ports":1},
{"model":"beta", "ports":43},
{"model":"gamma", "ports":66},
{"model":"omega", "ports":6},
{"model":"omega", "ports":1}];
console.log(processData(data));