简体   繁体   English

如何将键/值对从 for 循环推送到现有的对象数组

[英]How to push key/value pairs from for loop to existing array of objects

I'm trying to figure out how to properly push my key/value pairs that are returned from my for loop into an existing array of objects.我试图弄清楚如何正确地将从我的 for 循环返回的键/值对推送到现有的对象数组中。 As is stands right now, every time the for loop is ran, it pushes the new key/pair values to the array and removes the previous values.就像现在一样,每次运行 for 循环时,它都会将新的键/对值推送到数组并删除以前的值。

setLabels is called on a click event and pulls values from this.state.exportEntries. setLabels 在单击事件上调用并从 this.state.exportEntries 中提取值。

I'd like to push the values, from the for loop, to fillerArray without removing any data on setLabels rerun.我想将值从 for 循环推送到 fillArray 而不删除 setLabels 重新运行的任何数据。 Could someone point me in the right direction for achieving this?有人可以指出我实现这一目标的正确方向吗?

Based on other users comments, a merge is what I'm looking for.根据其他用户的评论,我正在寻找合并。 However, as stated, I am working within a for loop and do not have two or more clearly defined arrays like array1 / array2 to merge.但是,如上所述,我在 for 循环中工作,并且没有两个或多个明确定义的数组(如 array1 / array2)进行合并。

The data gets pushed to fillerArray on every for loop and that is what's resetting it.数据在每个 for 循环中被推送到 fillArray,这就是重置它的原因。 However, I'm wondering if it's possible to preserver the previous values in fillerArray while adding to it on the next for loop.但是,我想知道是否可以在下一个 for 循环中添加到之前的值时保留之前的值。

If any further information is needed, please let me know.如果需要任何进一步的信息,请告诉我。

Code Structure代码结构

setLabels = (e, itemId, itemLabel) => {

  let fillerArray = [];

  for (let item of this.state.exportEntries) {
    if (itemId in item) {
      fillerArray.push({ [itemLabel]: item[itemId] });
    }
  }

console.log(fillerArray);

}

Current Output电流输出

(7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}]
  0: {First: "Name1"}
  1: {First: "Name2"}
  2: {First: "Name3"}
  3: {First: "Name4"}
  4: {First: "Name5"}
  5: {First: "Name6"}
  6: {First: "Name7"}
  length: 7
  __proto__: Array(0)

(7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}]
  0: {Last: "Last1"}
  1: {Last: "Last2"}
  2: {Last: "Last3"}
  3: {Last: "Last4"}
  4: {Last: "Last5"}
  5: {Last: "Last6"}
  6: {Last: "Last7"}
  length: 7
  __proto__: Array(0)

Desired Output期望输出

(7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}]
  0: {First: "Name1", Last: "Last1"}
  1: {First: "Name2", Last: "Last2"}
  2: {First: "Name3", Last: "Last3"}
  3: {First: "Name4", Last: "Last4"}
  4: {First: "Name5", Last: "Last5"}
  5: {First: "Name6", Last: "Last6"}
  6: {First: "Name7", Last: "Last7"}
  length: 7
  __proto__: Array(0)

You want to merge two equally long arrays of object which can be done in the following manner:您想合并两个同样长的对象数组,可以通过以下方式完成:

let merged = [];
for(var i = 0; i < array1.length; i++) {
    merged.push({...array1[i], ...array2[i]})
}

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

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