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)