I wanna set the value in a JSON using a path string like this "a.0.b"
for a JSON that looks like this:
{
a: [
{
b: 'c'
}
]
}
I came up with this solution but I wonder if there is a simpler way to write this:
function setValue(path, value, json) {
var keys = path.split('.');
_.reduce(keys, function(obj, key, i) {
if (i === keys.length - 1) {
obj[key] = value;
} else {
return obj[key];
}
}, json);
}
so calling setValue('a.0.b', 'd', {a:[{b:'c'}]})
would change the json to {a:[{b:'d'}]}
I wanna set the value in a JSON using a path string like this "a.0.b"
for a JSON that looks like this:
{
a: [
{
b: 'c'
}
]
}
I came up with this solution but I wonder if there is a simpler way to write this:
function setValue(path, value, json) {
var keys = path.split('.');
_.reduce(keys, function(obj, key, i) {
if (i === keys.length - 1) {
obj[key] = value;
} else {
return obj[key];
}
}, json);
}
so calling setValue('a.0.b', 'd', {a:[{b:'c'}]})
would change the json to {a:[{b:'d'}]}
- FYI, JSON is a textual data-exchange format. What you are referring to in your question is a (nested) JavaScript object/array. – Felix Kling Commented Apr 8, 2013 at 9:24
-
So would you like to set variables like
a[0].b = 1;
, or am I pletely wrong? – Qantas 94 Heavy Commented Apr 8, 2013 at 10:40 -
In the
setvalue
would be passed a the path string, the new value and the json where the value should changed. Updated the question with an example. – Andreas Köberle Commented Apr 8, 2013 at 10:47 -
1
In your example the
a
array does not contain a key of'0'
(a string). You would have to convert the string into an integer to access the first index of thea
array. – idbehold Commented Apr 8, 2013 at 12:32 - To be clear the posted function works well, I just wonder if the function could be simplified. – Andreas Köberle Commented Apr 8, 2013 at 12:37
1 Answer
Reset to default 4Here's a solution. I benchmarked the two possible solutions and it seems looping over object and path is faster than using the reduce function. See the JSPerf tests here: http://jsperf./set-value-in-json-by-a-path-using-lodash-or-underscore
function setValue(path, val, obj) {
var fields = path.split('.');
var result = obj;
for (var i = 0, n = fields.length; i < n && result !== undefined; i++) {
var field = fields[i];
if (i === n - 1) {
result[field] = val;
} else {
if (typeof result[field] === 'undefined' || !_.isObject(result[field])) {
result[field] = {};
}
result = result[field];
}
}
}