什么是重组的最佳方式array
进入output
?我需要将所有值键(无论是否为数组)合并到共享相同名称键的对象中。这里有类似的东西,但是因为我也有数组,所以不能回答我的问题。
var array = [
{
name: "foo1",
value: "val1"
}, {
name: "foo1",
value: [
"val2",
"val3"
]
}, {
name: "foo2",
value: "val4"
}
];
var output = [
{
name: "foo1",
value: [
"val1",
"val2",
"val3"
]
}, {
name: "foo2",
value: [
"val4"
]
}
];
是的,我可以编写无限for
循环和介于两者之间的多个数组,但是有没有简单的快捷方式?谢谢!
这是一个选择:
var array = [{
name: "foo1",
value: "val1"
}, {
name: "foo1",
value: ["val2", "val3"]
}, {
name: "foo2",
value: "val4"
}];
var output = [];
array.forEach(function(item) {
var existing = output.filter(function(v, i) {
return v.name == item.name;
});
if (existing.length) {
var existingIndex = output.indexOf(existing[0]);
output[existingIndex].value = output[existingIndex].value.concat(item.value);
} else {
if (typeof item.value == 'string')
item.value = [item.value];
output.push(item);
}
});
console.dir(output);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句