-3

I have an object

let a = {b : {c : "d"}}

And i have the property who must change with a new value

let prop = "b.c";
let newValue = "e";

So, in my object, the "c" must be edited with the new value.

i tried

a[prop] = newValue; // but it create "b.c" property

let fields = prop.split('.');
a[fields] = newValue; // but it create "b,c" property

// all i want is a dynamic way to do
a[fields[0]][fields[1]] = newValue;

is it possible ?

thanks

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Maxime Girou
  • 1,511
  • 2
  • 16
  • 32
  • 1
    `{b : c : {"d"}}` is not valid syntax. – ASDFGerte Nov 26 '19 at 15:13
  • 2
    Is your object meant to be `let a = {b : {c : "d"}}`? – Jamiec Nov 26 '19 at 15:13
  • My bad, i edited – Maxime Girou Nov 26 '19 at 15:14
  • Does this answer your question? [Accessing nested JavaScript objects with string key](https://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key) – ASDFGerte Nov 26 '19 at 15:15
  • 1
    `let newValue : "e";` is invalid syntax aswell btw. – ASDFGerte Nov 26 '19 at 15:16
  • 1
    Your best bet would using something like [`_.set` from Lodash](https://lodash.com/docs/4.17.15#set). The alternative is to re-implement this functionality. That's not *hard* but it depends on how much error handling you want to do and how much syntax you want to support. Lodash already has both of these. – VLAZ Nov 26 '19 at 15:16

1 Answers1

2

Using reduce()

let a = {b : {c : "d"}}

let prop = "b.c"
let newValue = "e"

prop.split('.').reduce((a, o) =>
  Object(a[o]) === a[o] ? a[o] : a[o] = newValue
, a)

console.log(a)
User863
  • 19,346
  • 2
  • 17
  • 41