我每次选择一个值时都会有一个对象数组,将其推入数组时,我想合并具有相同键(即键“ code”)的两个对象,并删除空值
(4) [{…}, {…}, {…}, {…}]
0: {code: "abc", value: "", access: "A"}
1: {code: "abc", value: "ok", access: ""}
2: {code: "def", value: "xyz", access: ""}
3: {code: "def", value: "", access: "B"}
the output should be
(2) [{…},{…}]
0: { code: "abc", value: "ok", access: "A"}
1: {code: "def", value: "xyz", access: "B"}
我已经尝试了传播算子,但它不起作用。请帮帮我
您可以使用.reduce(..),这是一个示例:
const input = [
{code: "abc", value: "", access: "A"},
{code: "abc", value: "ok", access: ""},
{code: "def", value: "xyz", access: ""},
{code: "def", value: "", access: "B"}
];
const output = input.reduce((a, c) => {
const found = a.find(({ code }) => c.code === code);
if (found) {
Object.entries(c).forEach(([key, value]) => {
if (!found[key]) {
found[key] = value;
}
});
} else {
a.push(c);
}
return a;
}, []);
console.log(output);
即使对于示例输入正确运行,在某些情况下也会失败,因为它将替换所有可能不是您想要的虚假值(布尔值false
,数字0
等)。
为避免这种!found[key]
情况,if
请使用适合您需要的任何检查替换语句中的条件。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句