javascript - 连接 2 个相似对象 javaScript 的所有属性

标签 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;
}

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

最佳答案

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

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

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/

相关文章:

python - Concat DataFrames 对角线

javascript - jQuery 听起来 IE7/IE8 与 FlashExternalInterface 存在问题

javascript - 谷歌可视化运动图表未定义?

iteration - SICP - 我对阶乘迭代过程的递归定义不好吗?

boost - 迭代多级 boost 树

c++ - TSP递归解决方案的迭代形式

javascript - 将子元素追加到父元素中

javascript - webex 干扰 Web 应用程序

php - 显示正确的 mysql 连接的问题

javascript - 如何将数组的一项与数组的另一项连接