什么是重组的最佳方式array进入output?我需要将所有值键(无论是否为数组)合并到共享相同名称键的对象中
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循环和介于两者之间的多个数组,但是是否有一个简单的快捷方式?谢谢!
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);