我有两个对象,如果两个道具具有相同的键,我需要合并它们并连接字符串
我有两个对象,如果两个道具具有相同的键,我需要合并它们并连接字符串 注意:我正在使用 lodash.js
obj1 = {
name: 'john',
address: 'cairo'
}
obj2 = {
num : '1',
address: 'egypt'
}
我需要合并的对象如下:
merged = {name:"john", num: "1", address:"cairo,Egypt"}
当我尝试使用时,地址属性的问题 _.defaults(obj1,obj2) 或者 _.merge(obj1,obj2)
地址值将是 obj2 内的地址 prop 的值 所以我需要一种方法来合并两个对象并连接每个对象中的两个地址道具。
I have two objects and i need to merge them and concat strings if two props have the same key
note: I'm using lodash.js
obj1 = {
name: 'john',
address: 'cairo'
}
obj2 = {
num : '1',
address: 'egypt'
}
I need the merged object to be like:
merged = {name:"john", num: "1", address:"cairo,Egypt"}
the issue with address prop when I'm trying to use
_.defaults(obj1,obj2)
or
_.merge(obj1,obj2)
the address value will be the value of the address prop inside obj2
so I need a way to merge the two objects and concat the two address props in each object.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
试试这个:
Try this:
您甚至不需要
lodash
。您可以轻松地为此创建自己的函数。您可以这样做:new Set
- 查找两个输入对象中所有唯一的键for...of
- 迭代唯一的上面计算出的键You don't even need
lodash
. You can easily create you own function for that. You can do it like this:new Set
- to find all unique keys across both input objectsfor...of
- to iterate over unique keys calculated above这样您就可以合并任意数量的对象!
This way you can merge any number of objects!
您可以使用
_.mergeWith()
将特定键的值连接到数组,然后使用_.mapValues()
将数组连接到字符串:You can use
_.mergeWith()
to concat the values of specific keys to arrays, and then use_.mapValues()
to join the arrays to strings: