-1

I want to replace "placeholder" with {"John": "Dough"} dynamically with a function call.

This works:

a = {foo:{bar:{baz:"placeholder"}}};
a.foo.bar.baz = {"John" : "Dough"};
console.log(JSON.stringify(a)); 

> {"foo":{"bar":{"baz":{"John":"Dough"}}}}

But this doesn't:

var test = function(key, value) {
    a = {foo:{bar:{baz:"placeholder"}}};
    a.foo.bar.baz = { key: value};
    console.log(JSON.stringify(a));
    };
test("John", "Dough");

> {"foo":{"bar":{"baz":{"key":"Dough"}}}}

This also doesn't work:

var test = function(key, value) {
    a = {foo:{bar:{baz:"placeholder"}}};
    a.foo.bar.baz[key] = value;
    console.log(JSON.stringify(a));
    };
test("John", "Dough");

> {"foo":{"bar":{"baz":"placeholder"}}}

I am testing on Node.js. Probably won't change in browser.

rsa
  • 102
  • 2
  • 8
  • there is no such thing "json object" in java script. there's json, which is the serielized form of an object, and an object. period. saying json object it's like saying "cake-recipe cake", either it's a recipe cake, either it's a cake. there's no between. – David Haim Sep 10 '15 at 08:33
  • @ArunPJohny - This question is not answered by the one you refer to as a duplicate. This question is asking how to replace a property. If you actually look at the code supplied then you can see that the OP already knows how to dynamically refer to properties using variables as key names. He does it. Stop before you mark as duplicate in future. – Reinstate Monica Cellio Sep 10 '15 at 08:39
  • @DavidHaim I corrected the title. – rsa Sep 10 '15 at 09:13

1 Answers1

1

Change your function as bellow

var test = function(key, value) {
    a = {foo:{bar:{baz:"placeholder"}}};
    a.foo.bar.baz = {};   //creating a new object as `baz` value then assign
    a.foo.bar.baz[key] = value;
    console.log(JSON.stringify(a));
};
Mritunjay
  • 25,338
  • 7
  • 55
  • 68