2
c.key = "test";
a = {};
a.body = {};
a.body.interval={}; 
a.body.interval = c.key;

b = {};
b.body = {};
b.body.interval={}; 
b.body.interval = c.key;  

c["key"]="sample";

return JSON.stringify(a);

I want to change all the values which are referred by mentioned variable in javascript.

Currently, this print

{"body":{"interval":"test"}}

I want to change properties referred by c.key. I can not change individual properties of JSON as those are not fixed.

How can I change all the properties referred by an individual variable in javascript?

7
  • You can't determine at runtime whether a variable is actually a reference to another variable(or property/key in your case). What exactly are you trying to achieve here? Commented Jun 14, 2017 at 0:17
  • I have to set different properties after some time when I get the actual value. Those different properties share the same value, so I want to set them later when I have the value Commented Jun 14, 2017 at 0:18
  • You need an identification mechanism on each key you want to update. Then just explicitly update those fields when your actual value arrives Commented Jun 14, 2017 at 0:19
  • I do not want to individual update on the field, that is the reason I need some pass by reference mechanism which changes the underlying properties Commented Jun 14, 2017 at 0:22
  • What do you understand the meaning of "change a JSON property" to be? A JSON string is a snapshot, in JavvaScript Object Notation format, of some properties of an object. Just use the object if it's properties are changing. Commented Jun 14, 2017 at 0:22

1 Answer 1

2

Not sure if this is exactly what you want but using a function instead of a variable can solve your problem. (since you can pass a replace function to stringify.

take a look at the following code:

c = {};
c.key = "test"

a = {};
a.body = {};
a.body.interval = function(){return c.key};

c["key"]="sample";

JSON.stringify(a, function (key, value) {
        if (key == 'interval') {
            return value();
        } else {
            return value;
        }
    });

c = {};
c.key = "test"

a = {};
a.body = {};
a.body.interval = function(){return c.key};

c["key"]="sample";

out = JSON.stringify(a, function (key, value) {
        if (key == 'interval') {
            return value();
        } else {
            return value;
        }
    });
    
console.log(out);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.