2

that is suppose to come 1,2,3 but coming 3,3,3, how to fix that ? Javascript updating automatically

let test = [ { id: 1 } ];
let test2 = [
  { id: 1 },
  { id: 2 },
  { id: 3 }
];

let x = []

test2.forEach(i => {
  test[0].id = i.id;
  x.push(test[0])
});

console.log(x)

3
  • x.push({ ...test[0] }); Commented Jul 13, 2021 at 7:42
  • test[0] is a reference to the object at index 0. After the .forEach() x has test2.length copies of that one reference. Commented Jul 13, 2021 at 7:42
  • 1
    It's a dupe of How do I correctly clone a JavaScript object? - in some way... Commented Jul 13, 2021 at 7:46

3 Answers 3

2

Since you are pushing the same object 3 times and at the end of the loop it will have 3 reference of the same object i.e test[0]

You can use spread syntax to copy all properties of object

let test = [{ id: 1 }];
let test2 = [{ id: 1 }, { id: 2 }, { id: 3 }];

let x = [];

test2.forEach((i) => {
  test[0].id = i.id;
  x.push({ ...test[0] });
});

console.log(x);

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

1 Comment

"it will have 3 copies of object" - If that would be the case then the problem as observed by OP would not exist. .push(test[0]) pushes references to the object at index 0 and not a copy of the object
1

Use the spread operator:

x.push({ ...test[0] })

Basically you need to shallow clone the array because it's an object; forEach will create 3 references to the same test[0] object at the beginning of the call.

Comments

0

You are passing in the same reference to the array everytime. You are updating that same value too i.e., test[0].

So in the end, you have an array with three elements, all 3 pointing to the same object whose id property you have updated to the final value - test2[2].id.

You can directly push in an object with the correct id property. You will not need an extra test array as you are creating your object and pushing them on the go.

let test = [ { id: 1 } ];
let test2 = [
  { id: 1 },
  { id: 2 },
  { id: 3 }
];

let x = []

test2.forEach(i => {
  x.push({ id : i.id })
});

console.log(x)

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.