简体   繁体   中英

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. 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.

setLabels is called on a click event and pulls values from this.state.exportEntries.

I'd like to push the values, from the for loop, to fillerArray without removing any data on setLabels rerun. 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.

The data gets pushed to fillerArray on every for loop and that is what's resetting it. However, I'm wondering if it's possible to preserver the previous values in fillerArray while adding to it on the next for loop.

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]})
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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