Vivek V Dwivedi Vivek V Dwivedi - 29 days ago 9
Javascript Question

Update values in a json object based on dynamic keys available as array

I have a json object like this:

var obj = {
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}


This JSON can be any valid JSON. Now I want to access and update some property based on an array available to me like this:

['glossary', 'GlossDiv', 'GlossList', 'GlossEntry', 'SortAs'] // any dynamic but valid path


So given the above array, I want to access

obj['glossary']['GlossDiv']['GlossList']['GlossEntry']['SortAs']


so that I can update its value. I have
config(or any such json)
as an instance variable, so I want to directly update that rather than creating a new json and then replacing the entire
config
object. I have access to jQuery, underscore, backbone and of course plain old JS.

Answer

You could reduce the object with walking the path.

function getValue(object, path) {
    return path.reduce(function (o, k) {
        return (o || {})[k];
    }, object);
}

var object = { glossary: { title: "example glossary", GlossDiv: { title: "S", GlossList: { GlossEntry: { ID: "SGML", SortAs: "SGML", GlossTerm: "Standard Generalized Markup Language", Acronym: "SGML", Abbrev: "ISO 8879:1986", GlossDef: { para: "A meta-markup language, used to create markup languages such as DocBook.", GlossSeeAlso: ["GML", "XML"] }, GlossSee: "markup" } } } } };

console.log(getValue(object, ['glossary', 'GlossDiv', 'GlossList', 'GlossEntry', 'SortAs']));

Comments