gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:22:17 26 4
gpt4 key购买 nike

我有 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com