tech snake
tech snake

Reputation: 95

javascript pushing an object to an array object but other object affected

My problem is when I add a new object to an array object, the last object fields overwrite the other objects fields. At the end, all objects become the same. Here is the example

array=[{id:1 names:[john,james,alice]},
       {id:2 names:[lisa,carlos,josh]}]

var obj={id:3 names:[david]}

array.push(obj)

console.log(array)

 //=>      [{id:1 names:[david]},
            {id:2 names:[david]},
            {id:3 names:[david]}]

I am having the same problem when try to delete one of them. What are your suggestions?

Upvotes: 0

Views: 152

Answers (5)

Rohìt Jíndal
Rohìt Jíndal

Reputation: 27192

Your JSON is not a valid JSON otherwise your code is working fine.

enter image description here

Working Demo :

var array=[{id:1, names:["john","james","alice"]},
       {id:2, names:["lisa","carlos","josh"]}]

var obj={id:3, names:["david"]}

array.push(obj);

console.log(array);

Upvotes: 0

Priyangna
Priyangna

Reputation: 61

You have to put string in quotes, otherwise it will be remain undefined.Comma (,) is missing after id in array. Try below code-

 var array=[{id:1, names:["john","james","alice"]}, {id:2, names:["lisa","carlos","josh"]}];

        var obj={id:3, names:["david"]};

        array.push(obj);

        for(z=0;z<array.length;z++){

           alert(array[z])  ;

        }

Upvotes: 0

caramba
caramba

Reputation: 22480

You are missing some apostrophes and comas.

array = [
  { id: 1, names: ['john', 'james', 'alice']},
  { id: 2, names: ['lisa', 'carlos', 'josh']}
];

var obj={ id:3, names: ['david']}

array.push(obj)

console.log(array)

Upvotes: 3

Gabri T
Gabri T

Reputation: 454

    array=[{id:1, names:["john","james","alice"]},
           {id:2, names:["lisa","carlos","josh"]}];
    
    var obj={id:3, names:["david"]};
    
    array.push(obj);
    
    alert(array[0].names);
    
    alert(array[1].names);
    
    alert(array[2].names);

seems like your code was kinda messy. Here is a correct version

Upvotes: 0

Tareq
Tareq

Reputation: 5363

You Js is invalid. Try something like below:

var array =[
  {id:1, names:['john', 'james', 'alice']},
   {id:2, names:['lisa', 'carlos', 'josh']}]

var obj= {id:3, names:['david']}

array.push(obj)

console.log('array => ', array)

Upvotes: 0

Related Questions