Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop through object array and change the values

Tags:

javascript

i am trying to loop through an object array (not sure if that is correct terminoledgy) and want to change the values to each key within the list.

example if I have a list of room1 = 0, room2 = 0, room3 = 0 and after i have looped through it will be room1 = 10, room2 = 10, room3 = 10.

I can do it with an array but will then loose the keys which is very helpfull when using the array in other parts of my program.

I understand this has been asked before but cannot see a solution to changing the values

My code below changes the values within the loop but the console log outside the loop shows room2 is still equal 0

Any help please or is this something that cannot be done

temps = {room1:0, room2:0, room3:0};
const entries = Object.entries(temps);
for (i=0; i<3; i++){
  entries[i][1] = 10;
  console.log(entries[i]);
}
console.log("room2 = " + temps.room2);

2 Answers

You can just loop over the keys, you don't want Object.entries in this case because it's not giving you a reference into the original object:

let temps = {room1:0, room2:0, room3:0};
for (let key in temps) {
  temps[key] = 10
}
console.log(temps)
console.log("room2 = " + temps.room2);
like image 138
Mark Avatar answered Feb 06 '26 14:02

Mark


The problem you have is you are just altering the entries array and that has no relationship back to the parent. Changing it does not change the parent since it is just a copy of the keys and values, it is not a reference to them.

So you need to alter the actual object. You can just iterate over the keys and alter the object. forEach loop makes it easy.

const temps = {room1:0, room2:0, room3:0};
Object.keys(temps).forEach( function (key) {
  temps[key] = 10;
});
console.log(temps)
like image 30
epascarello Avatar answered Feb 06 '26 14:02

epascarello



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!