简体   繁体   English

如何将所有键/值对从 forEach 推送到对象

[英]How to push all key/value pairs to object from forEach

I'm running my array of objects (this.state.exportEntries) through a for loop that is then comparing the itemId to the key within the object returned within the for loop.我正在通过 for 循环运行我的对象数组 (this.state.exportEntries),然后将 itemId 与 for 循环中返回的对象内的键进行比较。 If the key matches itemId, then run a forEach to push that key/value to the filteredData object.如果键匹配 itemId,则运行 forEach 将该键/值推送到过滤数据对象。

My issue is that, if I have more than one value that matches, the forEach only pushes the last returned value to the filteredData object.我的问题是,如果我有多个匹配的值,则 forEach 只会将最后一个返回值推送到过滤数据对象。

Could anyone help me understand how to push all returned values to the filteredData object?谁能帮助我理解如何将所有返回值推送到过滤数据对象? As you can see in the output of this.state.filteredData, only the last key/value pair that is matched gets pushed to filteredData.正如你在 this.state.filteredData 的输出中看到的,只有最后匹配的键/值对才会被推送到filteredData。

Code Structure代码结构

for (let item of this.state.exportEntries) {

  console.log(item);

  Object.entries(item)
    .filter(([key,]) => key === itemId)
    .forEach(([key, value]) => (this.state.filteredData[key] = value));

}

console.log(this.state.filteredData);

Output of item项目输出

{1.2: "1", 1.3: "1"}

{1.2: "2", 1.3: "2"}

{1.2: "3", 1.3: "3"}

{1.2: "4", 1.3: "4"}

Output of this.state.filteredData this.state.filteredData 的输出

{1.3: "4"}

Desired Result想要的结果

{
 1.3: "1, 2, 3, 4"
}

You need not to iterate the entries, because you have already a key itemId for the object.您不需要迭代条目,因为您已经有对象的关键itemId

for (let item of this.state.exportEntries) {
    console.log(item);
    if (itemId in item) {
        if (!this.state.filteredData[itemId]) this.state.filteredData[itemId] = item[itemID];
        else this.state.filteredData[itemId] += ', ' + item[itemID];
    }
}

console.log(this.state.filteredData);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM