0
var dd = [];
const ff = { };
ff.dd = 0;
dd.push(ff);
console.log(dd);
ff.dd = 1;
dd.push(ff);
console.log(dd);

I am getting output

[ { dd: 0 } ]
[ { dd: 1 }, { dd: 1 } ]

but I want the output to be like

[ { dd: 0 } ]
[ { dd: 0 }, { dd: 1 } ]
1
  • 2
    Strongly recommend not using the same identifier (dd) for two entirely different things when asking questions, it makes both the question and its potential answers unnecessarily complicated. Commented Dec 17, 2017 at 9:42

3 Answers 3

1

To get that output, you'd have to create a new object (ff), instead of modifying the existing one.

var dd = [];
let ff = { };     // <== `let` instead of `const`
ff.dd = 0;
dd.push(ff);
console.log(dd);
ff = { };         // <== Create a new object
ff.dd = 1;
dd.push(ff);
console.log(dd);


Side note: You don't need ff at all:

var dd = [];
dd.push({dd: 0});
dd.push({dd: 1});
console.log(dd);

...and in fact the whole thing can be done in one initializer:

var dd = [
  {dd: 0},
  {dd: 1}
];
console.log(dd);

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

2 Comments

But i should use one object for assign data .what should i do?
@viswaram: You can't use just one object; the output you want clearly shows an array with two objects in it with different contents (different dd properties).
1

Javascript keeps references to objects. In your code, you initially push the ff variable with dd set to 0. Then you modify the dd value of the same ff variable and push another reference to it into the array. That is why you get an array with 2 references to the same ff object with dd value of 1.

If you want to achieve the result you wrote you need to create a new object before pushing it again into the array.

Comments

1

If your ff always is of one level deep, you can use Object.assign to clone ff each time you put it into the array.

var ffCopy = Object.assign({}, ff);

var dd = [];
const ff = { };
ff.dd = 0;
dd.push(Object.assign({}, ff));
console.log(dd);
ff.dd = 1;
dd.push(Object.assign({}, ff));
console.log(dd);

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.