Using for...in to mutate the original object

var data = [
 {
    item: "hello world",
    otheritem: "asdf",
 },
 {
    item: "hello0 wo0rld",
    otheritem: "as1df",
 },
]

for (var i = 0; i < data.length; i++) {
    for (key in data[i]) {
        key = key + "a"
        console.log(data)
    }
}

:arrow_forward:on Runkit

I have an array of objects, and want to change the value of each key - I have a for…in loop inside of a for loop to go through the array. Any thoughts on why the original array is unchanged?

Instead of using nested for loops, you can use the Array#map function.

Warning: untested code ahead!

var modifiedArray = data.map(obj => {
   obj.item += "a";
   return obj;
});

Array#map returns a new array with the modified values.

1 Like

Hmmm, I’ll try that. I was trying to avoid making a new array though, because this is for mass database editing.

key in the loop is its own variable with a string value. It’s not a reference to some part of an object from before. That’s why when you assign something else to it here

it doesn’t change the objects in the array.

1 Like

Oh, I see - thanks for the clarification! Is there a way to get the value of the key? like, if (key === item) do something…

Rather than using a for ... in ..., you could use the array/object.forEach() nethod. You can add an arguement that returns the index for and array or key for an object:

objecr.forEach((item, key) => {
  doSomething();
});
1 Like

Interesting, didn’t know forEach works with objects. I’ll try this today.

Sorry for bumping this, but I realised thst my post was incorrect. object.forEach() does not work. Instead, use Object.entries(object).foreach([key, value] => {...});.

1 Like

Thanks pufferfish, you are too OP lol. I largely forgot about this :sweat_smile: I’ll look into object.entries.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.