0

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?

1
  • You need to show valid non-working JavaScript, which that is not. Commented May 26, 2017 at 9:44

5 Answers 5

3

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

0

    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

Comments

0

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

        }

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.