【发布时间】:2020-04-21 23:39:31
【问题描述】:
我正在运行一个 for...of 循环。我正在使用的配置文件config 循环了两次,我想要的是采用这两个配置并将它们都添加到 Javascript 对象中。我遇到的问题是,当我使用扩展语法将来自第一个循环的数据与来自第二个循环的数据合并时,来自第二个循环的数据将覆盖整个对象而不是合并。 (下面函数中不相关的部分我已经去掉了)
Datasets() {
var newObject = {};
var config = ConfigFile;
for (const [h_name, h_config] of Object.entries(config)) {
var d = new datasetobj(h_name, this.configuration);
var mergedObj = { ...d, ...h_config }; // this works fine and merges the 2 objects together as expected
console.log(newObject); // This shows an empty object the first loop (as expected), then it shows the correct data from the first loop in the second loop.
newObject = { ...newObject, ...mergedObj }; // Here, instead of merging the objects, it is overwriting the entire object with mergedObj
console.log(newObject);
}
}
我期望 newObject 发生的事情是:{ } -> {a} -> {ab}
实际发生的情况是:{ } -> {a} -> {b}
【问题讨论】:
-
你能在codesandbox/jsfiddle中重现问题吗?看代码好像没有什么问题,除非newObject和mergedObj都是空的。
-
好的,这里是链接:jsfiddle.net/2topher/p3fk17v0/1
-
jsfiddle 中的控制台输出看起来有点奇怪,因为我没有提取实际数据,但您仍然可以看到问题。我可以确认 newObject 仅在循环之前最初创建时为空,并且 mergeObj 也不为空。
标签: node.js for-loop javascript-objects