我有 2 个不同的对象,它们具有我想要连接的相同属性:
obj1 = {id: "1: identifier 1 \n", description: "1: description 1 \n", ...., propertyX1}
obj2 = {id: "2: identifier 2 \n", description: "2: description 2 \n", ...., propertyX2}
我的结果应该是:
obj1 = {id: "1: identifier 1 \n 2: identifier 2 \n",
description: "1: description 1 \n 2: description 2",
....,
propertyX1|propertyX2}
目前我的解决方案是:
function combineElements(element1, element2){
var property1, property2;
for (property1 in element1) {
if(element1.hasOwnProperty(property1)) {//bonus question: why does intellij ask me to add this?
property2 = element2.getSameProperty(property1); // <<<<<<how do I iterate this?
property1 = "\n" + property2;
}
}
return element1;
}
如何获得与第二个元素完全相同的属性?
最佳答案
您可以连接所有具有相同名称的属性。
技术使用(按出现顺序):
- >
Array#reduce
- > arrow functions
- >
Object.assign
- > spread syntax
...
- >
Object.entries
- >
Array#map
- > destructuring assignment
- > computed property names ,比如
{ [k]: value }
(k
是属性的名称) - > logical OR
||
参加 truthy值(value)
var obj1 = { id: "1: identifier 1 \n", description: "1: description 1 \n", propertyX1: 'propertyX1' },
obj2 = { id: "2: identifier 2 \n", description: "2: description 2 \n", propertyX2: 'propertyX2' },
result = [obj1, obj2].reduce(
(r, o) => Object.assign(r, ...Object.entries(o).map(([k, v]) => ({ [k]: (r[k] || '') + v }))),
{}
);
console.log(result);
关于javascript - 连接 2 个相似对象 javaScript 的所有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51454489/