代码之家  ›  专栏  ›  技术社区  ›  mBo

连接两个相似对象的所有属性javaScript

  •  1
  • mBo  · 技术社区  · 6 年前

    我有两个不同的对象,它们具有相同的属性,我要将它们连接起来:

    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 回复  |  直到 6 年前
        1
  •  3
  •   Nina Scholz    6 年前

    可以用相同的名称连接所有属性。

    使用的技术(按外观顺序排列):

    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);
        2
  •  2
  •   D. Seah    6 年前
    function combineElements(element1, element2) {
       Object.getOwnPropertyNames(element1).forEach(function(k1) {
           if (element2[k1]) {
             element1[k1] = element1[k1] + " " + element2[k1];
           }
       });
    }
    

    找到两个对象的匹配键

        3
  •  0
  •   Rohit.007    6 年前

    只需遍历其中一个对象,然后创建一个这样的新对象。

    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);
        4
  •  0
  •   Vignesh Raja    6 年前

    你可以用 Set 保存各个键并使用 Set.forEach Array.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)