连接2个类似对象的所有属性javaScript

时间:2018-07-21 09:00:12

标签: javascript iteration concatenation

我有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;
}

您将如何获得第二个元素的完全相同的属性?

4 个答案:

答案 0 :(得分:3)

您可以使用相同的名称合并所有属性。

技术使用(按出现的顺序):

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);

答案 1 :(得分:2)

term_id

找到2个对象的匹配键

答案 2 :(得分:0)

只需遍历其中一个对象,然后再创建一个新对象即可。

obj1 = {id: "1: identifier 1 \n", description: "1: description 1 \n"}
obj2 = {id: "2: identifier 2 \n", description: "2: description 2 \n"}

conObj = {};

for (var prop in obj1){
    if (obj1.hasOwnProperty(prop)) {
         conObj[prop] = obj1[prop] + obj2[prop];
    }
}

console.log(conObj);

答案 3 :(得分:0)

您可以使用Set来保存各个键,并使用Set.forEachArray.join进行迭代以连接值。

var obj1 = {id: "1: identifier 1 \n", description: "1: description 1 \n", propertyX1:"propertyX1", propertyX3:"propertyX3"};
var obj2 = {id: "2: identifier 2 \n", description: "2: description 2 \n", propertyX2:"propertyX2", propertyX4:"propertyX4"};

var keys = new Set(Object.keys(obj1).concat(Object.keys(obj2)));

var result={};

keys.forEach(function(key){
    result[key] = [obj1[key], obj2[key]].join(" ");
});

console.log(result)