T
T
TERRAN472018-02-17 22:35:19
JavaScript
TERRAN47, 2018-02-17 22:35:19

Does the entire array with objects change in the array?

https://codepen.io/anon/pen/QQamjX
there is also a description in css
The task is to change timeStart to true at the specified time in an array of attr objects
, the time is indicated in time
and it turns out it changes in the entire array
here is an example->
it will work if on the 10th line
transfer an array to a direct one, but it doesn’t work for me an array from redax, I get
grafik.forEach((elem)=>{
elem.attr = [{"title":"Hamam", "time":"1 hour 30 minutes", "timeStart ":false, "free":true},{"title":"Sauna", "time":"1 hour 30 min", "timeStart":false, "free":true}]
})

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-02-17
@TERRAN47

You are passing a reference to the same array to all elements of the graffik array :

grafik.forEach(elem => {
  elem.attr = attr; 
});

When you pass it directly, it works precisely because you create a new array with new objects each time.
You need to pass copies of the array with copies of nested objects. You can do it like this:
grafik.forEach(elem => {
  elem.attr = attr.map(el => ({ ...el }));
});

Or if you are not using the spread operator:
grafik.forEach(elem => {
  elem.attr = attr.map(el => Object.assign({}, el));
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question