0

I want to add an element to my array, but push just adds a new array

https://jsfiddle.net/jna79gs5/

var original = [{"Member_Name":"MORGAN, KATHY","Member_ID":"308484402","Member_DOB":"03/05/1998","ProgramType":"Supportive","RateCode":"000603"},{"Member_Name":"BUDZYNSKI, ALDA","Member_ID":"C436418737","Member_DOB":"11/30/1998","ProgramType":"Supportive","RateCode":"000603"},{"Member_Name":"MALLARI, SCOTT","Member_ID":"705681684","Member_DOB":"08/20/2002","ProgramType":"Supportive","RateCode":""}]

let newData = {name:"John", address:"432 main st"}; 
//let newData = [{"name":"John", "address":"432 main st"}]; 

const arr = [];
arr.push(original)
arr.push(newData)

console.log(arr);
  • Does this answer your question? [How to extend an existing JavaScript array with another array, without creating a new array](https://stackoverflow.com/questions/1374126/how-to-extend-an-existing-javascript-array-with-another-array-without-creating) – Clarity Dec 02 '19 at 18:21
  • Well, working with just numbers ends being different to me as I end up being distracted from looking at my actual objects and strings of data that I was getting a nested nightmare . I'm sure that answer if helpful to some, just not to me thx though –  Dec 02 '19 at 18:27

4 Answers4

3

You can't push an array to another array using push - JavaScript will just assume you meant to add the array as an element, rather than concatenating the array.

You'll want to use forEach:

const arr = [];
original.forEach(el => arr.push(el));
arr.push(newData);

Alternatively, you can use the array-spread operator:

const arr = [...original, newData];

Finally, you could use concat.

const arr = original.concat([newData]);
Dan
  • 10,282
  • 2
  • 37
  • 64
0

If i understand correctly, you are trying to merge arr and original ?
In that case, you can use concat().

var original = [{test: 'value'}]

let newData = {name:"John", address:"432 main st"}; 
//let newData = [{"name":"John", "address":"432 main st"}]; 

let arr = [];
arr = arr.concat(original)
arr.push(newData)

console.log(arr);
Nicolas
  • 8,077
  • 4
  • 21
  • 51
0

This is because you are creating 2 separate Arrays. const arr = [] and var original = [...] . And then you push original into arr, which creates the behaviour you don't want.

You dont need the const arr - you can just push newData into original

original.push(newData)

If you want to create another one then you can just use the spread operator.

const arr = [...original, newData];
Bioaim
  • 928
  • 1
  • 13
  • 26
0

Use array-Spread Operator

const arr =[...original,newData];