如何在 JavaScript 中将两个对象合并到同一个属性中?

Posted

技术标签:

【中文标题】如何在 JavaScript 中将两个对象合并到同一个属性中?【英文标题】:How can you merge two objects into same property in JavaScript? 【发布时间】:2020-11-16 14:59:45 【问题描述】:

我有 2 个单独的 JS 对象需要合并到同一个属性中。

对象当前如下所示:

对象 1:

[0:"acircuit":"ABCDEFGH","astatus":"Test", 1:"acircuit":"IJKLMNOP","astatus":"Test2"]

对象 2:

[0:"bcircuit":"ABCDEFGH","bstatus":"Test3", 1:"bcircuit":"IJKLMNOP","bstatus":"Test4"]

我需要将这些结果合并为一个,使其如下所示:

[
    0:"acircuit":"ABCDEFGH","astatus":"Test","bcircuit":"ABCDEFGH","bstatus":"Test3", 
    1:"acircuit":"IJKLMNOP","astatus":"Test2","bcircuit":"IJKLMNOP","bstatus":"Test4"
]

当前代码如下所示:

allResults = this.state.aCircuitResults.concat(this.state.bCircuitResults)

但是,结果如下所示:

[
    0:"acircuit":"ABCDEFGH","astatus":"Test",
    1:"acircuit":"IJKLMNOP","astatus":"Test2"
    2:"bcircuit":"ABCDEFGH","bstatus":"Test3", 
    3:"bcircuit":"IJKLMNOP","bstatus":"Test4"
]

提前致谢。

【问题讨论】:

【参考方案1】:

您可以使用mapObject.assign,假设您想通过它们在数组中的位置来组合它们:

const result = firstArray.map((firstObject, index) => Object.assign(, firstObject, secondArray[index]));

例子:

const firstArray = ["acircuit":"ABCDEFGH","astatus":"Test","acircuit":"IJKLMNOP","astatus":"Test2"];

const secondArray = ["bcircuit":"ABCDEFGH","bstatus":"Test3","bcircuit":"IJKLMNOP","bstatus":"Test4"];

const result = firstArray.map((firstObject, index) => Object.assign(, firstObject, secondArray[index]));

console.log(result);

如果您需要通过属性(例如,acircuitbcircuit)将它们关联起来,请从其中一个由该属性键入的 Map 构建一个 Map,然后您可以在 map 操作中使用查找:

const second = new Map(secondArray.map(obj => [obj.bcircuit, obj]));
const result = firstArray.map(firstObject => Object.assign(, firstObject, second.get(firstObject.acircuit)));

例子:

const firstArray = ["acircuit":"ABCDEFGH","astatus":"Test","acircuit":"IJKLMNOP","astatus":"Test2"];

const secondArray = ["bcircuit":"ABCDEFGH","bstatus":"Test3","bcircuit":"IJKLMNOP","bstatus":"Test4"];

const second = new Map(secondArray.map(obj => [obj.bcircuit, obj]));
const result = firstArray.map(firstObject => Object.assign(, firstObject, second.get(firstObject.acircuit)));

console.log(result);

【讨论】:

成功了 - 感谢您的帮助和快速响应。【参考方案2】:

Array.prototype.map() 与spread syntax 结合使用:

const result = arrayA.map((a, i) => (...a, ...arrayB[i]));

完成sn-p:

const arrayA = ["acircuit":"ABCDEFGH","astatus":"Test", "acircuit":"IJKLMNOP","astatus":"Test2"];
const arrayB = ["bcircuit":"ABCDEFGH","bstatus":"Test3", "bcircuit":"IJKLMNOP","bstatus":"Test4"];

const result = arrayA.map((a, i) => (...a, ...arrayB[i]));

console.log(result);

【讨论】:

以上是关于如何在 JavaScript 中将两个对象合并到同一个属性中?的主要内容,如果未能解决你的问题,请参考以下文章

如何根据javascript中的键合并和替换两个数组中的对象?

如何在javascript中将对象数组过滤为另一个对象数组? [关闭]

如何在 PySpark 中将两个 rdd 合并为一个

如何在响应中将两个变量合并为一个? [复制]

如何在Java中将两个PDF文件合并为一个?

如何在 Spark 中将两个 RDD[string] 合并在一起?