-2

Having an object like:

const myList = {
    object1: {
        type1: {
            val: 1
        }
    },
    object2: {
        type1: {
            val: 1
        }
    },
    object3: {
        type2: {
            val: 1
        }
    },
}

How would I override all val values nested in a type1?

SomeDutchGuy
  • 2,249
  • 4
  • 16
  • 42

2 Answers2

0

The following snippet should work.

for (const key in myList) {
  if ('type1' in myList[key]) {
    myList[key].type1.val = 'foo'
  }
}

The above example overrides all val in nested type1 to "foo".

msrumon
  • 1,250
  • 1
  • 10
  • 27
0

You are asking how to modify val in type1, so I am assuming there is a fixed path you want to access in your nested objects.
The easiest way is to loop through your objectN and use an hardcoded path:

for (const key of Object.keys(myList)) {
  myList[key].type1.val = newVal;
}

If you want a more dynamic solution to use to explore different paths in your nested object you could use array.prototype.reduce in a similar way:

function fromPathToObj(path, object) {
  // path = "type1.val"
  // path is splitted in valid keys, and they are used to access the values with reduce
  return path.split(".").reduce((acc, key) => acc[key],object);
}

The previous snippet would become

for (const key of Object.keys(myList)) {
  fromPathToObj("type1.val", myList[key]) = newVal;
}

Note: I'm not sure this second solution will modify the original object or you create deep copies of objectN with fromPathToObj, but I think it's worth trying.

Igor Cantele
  • 387
  • 1
  • 10