两个对象key相同的,值进行合并?
const a = {
fruits: ['apple', 'banana'],
series: {
apple: ['C'],
banana: ['A', 'B'],
}
};
const b = {
fruits: ['banana', 'orange'],
animals: ['pig'],
series: {
banana: ['B', 'C'],
orange: ['A'],
}
}
const merge = (a, b) => {
//...
}
// 期望输出:
{
fruits: ['apple', 'banana', 'orange'],
animals: ['pig'],
series: {
apple: ['C'],
banana: ['A', 'B', 'C'],
orange: ['A'],
}
}
回复
1个回答
test
2024-07-10
const merge = (a, b) => {
const result = {};
for (const key of Object.keys(a)) {
if (b.hasOwnProperty(key)) {
if (Array.isArray(a[key])) {
result[key] = [...new Set([...a[key], ...b[key]])];
} else if (typeof a[key] === 'object') {
result[key] = merge(a[key], b[key]);
} else {
result[key] = b[key];
}
} else {
result[key] = a[key];
}
}
for (const key of Object.keys(b)) {
if (!a.hasOwnProperty(key)) {
result[key] = b[key];
}
}
return result;
}
回复
适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容