0

This is my JSON variable.

var json = { input: "hello", payload: { pay1: 123, pay2: 456 } };

Now, I have a variable keypay1

var keypay1 = "payload.pay1";

Question 1: How can I get the value of json.payload.pay1 using just the dynamic variables json and keypay1??? I tried this and it gives me undefined.

console.log( json[keypay1] );

Similarly, Question 2: How can I set the value of json.payload.pay1 using just the dynamic variables json and keypay1???

Satpal
  • 132,252
  • 13
  • 159
  • 168
user3658423
  • 1,904
  • 5
  • 29
  • 49
  • Can't post the code for it since I am on my phone, but you need a loop, setting the object to the next level down and returning the end value. – Jhecht Dec 23 '14 at 07:57
  • could probably simplify how you create `keypay1` if this is it's sole use – charlietfl Dec 23 '14 at 08:04
  • 1
    `var keypay = "payload"; console.log(json[keypay].pay1)` something like this. – Jai Dec 23 '14 at 08:04
  • Assuming that you want to access the 123 value simply try out `console.log(json.payload.pay1)` you can access it as same. – Nagama Inamdar Dec 23 '14 at 08:05
  • how are you getting the strings for these properties like `'payload.pay1.offers.rank'`. Should look there to store differently – charlietfl Dec 23 '14 at 08:09

3 Answers3

2
var json = { input: "hello", payload: { pay1: 123, pay2: 456 } };

var parts = "payload.pay1".split('.');

// get the value
console.log(json[parts[0]][parts[1]]); // 123

// set the value
json[parts[0]][parts[1]] = "foo";
Ryan
  • 14,392
  • 8
  • 62
  • 102
  • It's better to use `hasOwnProperty` when you move into the JSON. Just to be failsafe. – Pataar Dec 23 '14 at 08:03
  • Ah nice..this works. But var keypay1 = "payload.pay1" is one example. What if variable has mutiple nodes example: payload.pay1.offers.rank - Is there an efficient and dynamic way to pass the split variable in JSON[]? – user3658423 Dec 23 '14 at 08:04
  • Not really. Your use case isn't generic, and every solution will be dependent on your input string. I suggest you ask another question if you want help on your other problem. – Ryan Dec 23 '14 at 08:05
  • @Pataar that makes no sense since `JSON` is a string data format and therefore would throw error using `hasOwnProperty` – charlietfl Dec 23 '14 at 08:06
  • @charlietfl So you are saying, that in this context, `var json = { input: "hello", payload: { pay1: 123, pay2: 456 } };` `json.hasOwnProperty("input");` would fail? – Pataar Dec 23 '14 at 08:08
  • 1
    @Pataar no that's not JSON as you were referring to it above – charlietfl Dec 23 '14 at 08:10
  • 2
    @charlietfl Perhaps I should've used 'Javascript object' instead of 'JSON' but still, in this context you should check if the property exists before doing something with it. – Pataar Dec 23 '14 at 08:12
  • 2
    @Pataar very valid, my main point is json isn't technically anyhting other than string yet the term gets used for object literals and arrays which does lead to confusion – charlietfl Dec 23 '14 at 08:16
  • @charlietfl I agree. – Pataar Dec 23 '14 at 08:17
0

Could use someting like this to use the "keypad" as a key to access a property on an object

// Split on . and browse myobject.
// Update context if property found and check again, else return null
var getModuleFromString = function(moduleName, myobject) {
    var fields = moduleName.split('.'), cur = myobject || window;
    for(var i=0; i<fields.length; i++){
        if(typeof cur[fields[i]] === "undefined") return null;
        cur = cur[fields[i]];
    }
    return cur;
};

var json = { input: "hello", payload: { pay1: 123, pay2: 456, pay3: { a:1, b:2 } } };
var keypay1 = "payload.pay1";

console.log(getModuleFromString(keypay1, json));
// 123

console.log(getModuleFromString("payload.pay3.a", json));
// 1
Hacketo
  • 4,978
  • 4
  • 19
  • 34
0

You could try looping through the properties.

function findProperty(jsonItem, key){
    for(var prop in jsonItem){
        if(typeof prop === 'object'){
            iterate(jsonItem[prop], key);
        } else if(key == prop){
            return jsonItem["prop"];
        }
    }
}

But that'll return only the first match it encounters.

John
  • 91
  • 4