gpt4 book ai didi

javascript - 将属性对象分配给具有相同属性的另一个现有对象

转载 作者:行者123 更新时间:2023-11-30 23:54:59 26 4
gpt4 key购买 nike

我想将第一个对象分配给具有相同属性的第二个对象。您建议什么快速方法?我需要单独循环存储对象吗?

第一个对象:

{
title: 'test',
description: 'desc',
tags: ['tag1','tag2']
}

第二个对象:

{
title: '',
description: '',
tags: [],
stores: [
{
id: 1,
title: '',
description: '',
tags: '',
template: '',
link: '',
active: true
},
{
id: 2,
title: '',
description: '',
tags: '',
template: '',
link: '',
active: false
}
]
}

结果:

{
title: 'test',
description: 'desc',
tags: ['tag1', 'tag2'],
stores: [
{
id: 1,
title: 'test',
description: 'desc',
tags: '['tag1', 'tag2']',
template: '',
link: '',
active: true
},
{
id: 2,
title: 'test',
description: 'desc',
tags: '['tag1', 'tag2']',
template: '',
link: '',
active: false
}
]
}

最佳答案

您可以使用对象扩展运算符进行浅层合并。

试试这个。

let obj1 = {
title: 'test',
description: 'desc',
tags: ['tag1', 'tag2']
};

let obj2 = {
title: '',
description: '',
tags: [],
stores: [
{
id: 1,
title: '',
description: '',
tags: '',
template: '',
link: '',
active: true
},
{
id: 2,
title: '',
description: '',
tags: '',
template: '',
link: '',
active: false
}
]
};

console.log({...obj2, ...obj1});

如果你想合并深度嵌套的对象,那么你可以使用下面的方法。

let obj1 = {
title: 'test',
description: 'desc',
tags: ['tag1', 'tag2']
};

let obj2 = {
title: '',
description: '',
tags: [],
stores: [
{
id: 1,
title: '',
description: '',
tags: '',
template: '',
link: '',
active: true
},
{
id: 2,
title: '',
description: '',
tags: '',
template: '',
link: '',
active: false
}
]
};

function isObject(item) {
return (item && typeof item === 'object' && !Array.isArray(item));
}

function deepMerge(target, ...sources) {
if (!sources.length) return target;
const source = sources.shift();
if (isObject(target) && isObject(source)) {
for (const key in source) {
if (isObject(source[key])) {
if (!target[key]) Object.assign(target, { [key]: {} });
mergeDeep(target[key], source[key]);
} else {
Object.assign(target, { [key]: source[key] });
}
}
}
return deepMerge(target, ...sources);
}

console.log(deepMerge(obj2, obj1));

关于javascript - 将属性对象分配给具有相同属性的另一个现有对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61113161/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com