gpt4 book ai didi

javascript - javascript中对象的递归合并

转载 作者:行者123 更新时间:2023-11-28 12:16:36 29 4
gpt4 key购买 nike

我目前正在使用 React 开发一个项目,并且在使用 setState 方法时合并两个对象时遇到问题。我有两个类似于的对象

person1 = {
name: 'ramya',
age: 21,
gender: 'f',
skills:{
technicalSkills: {
languages: ['C', 'C++', 'Java'],
operatingSystems: ['Unix', 'Linux']
},
linguisticSkills: {
toSpeak: ['English', 'Tamil'],
toRead: ['English']
}
},
}

obj2 = {
skills: {
linguisticSkills: {
toRead: ['English', 'Tamil']
}
}
}

我想将人员 1 的 Skills.linguisticSkills 状态更改为

linguisticSkills: {
toSpeak: ['English', 'Tamil'],
toRead: ['English', 'Tamil']
}

skills.linguisticSkills.toSpeakskills.linguisticSkills.toRead 不断变化,即添加或删除项目。每当它发生变化时,如何在 setState 中合并 person1 和 obj2 以便我最终处于正确的状态?

更新:_.merge 对于这样的情况会失败:

person1 = {
name: 'ramya',
age: 21,
gender: 'f',
skills:{
technicalSkills: {
languages: ['C', 'C++', 'Java'],
operatingSystems: ['Unix', 'Linux']
},
linguisticSkills: {
toSpeak: ['English', 'Tamil'],
toRead: ['English', 'Tamil', 'Telugu']
}
},
}

obj2 = {
skills: {
linguisticSkills: {
toRead: ['English', 'Tamil']
}
}
}

它给出的结果与第 1 个人相同,而

{
name: 'ramya',
age: 21,
gender: 'f',
skills:{
technicalSkills: {
languages: ['C', 'C++', 'Java'],
operatingSystems: ['Unix', 'Linux']
},
linguisticSkills: {
toSpeak: ['English', 'Tamil'],
toRead: ['English', 'Tamil']
}
},
}

预计。

最佳答案

洛达什的_.merge()是递归的。如果您需要对合并过程进行更精细的控制,可以使用 _.mergeWith() .

const person1 = {"name":"ramya","age":21,"gender":"f","skills":{"technicalSkills":{"languages":["C","C++","Java"],"operatingSystems":["Unix","Linux"]},"linguisticSkills":{"toSpeak":["English","Tamil"],"toRead":['English', 'Tamil', 'Telugu']}}}

const obj2 = {"skills":{"linguisticSkills":{"toRead":["English","Tamil"]}}}

const result = _.mergeWith({}, person1, obj2, (objValue, srcValue) => {
if( _.isArray(srcValue)) {
return srcValue;
}
});

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

关于javascript - javascript中对象的递归合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48294734/

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