Accessing nested JavaScript objects with string key
I have a data structure like this :
var someObject = {
'part1' : {
'name': 'Part 1',
'size': '20',
'qty' : '50'
},
'part2' : {
'name': 'Part 2',
'size': '15',
'qty' : '60'
},
'part3' : [
{
'name': 'Part 3A',
'size': '10',
'qty' : '20'
}, {
'name': 'Part 3B',
'size': '5',
'qty' : '20'
}, {
'name': 'Part 3C',
'size': '7.5',
'qty' : '20'
}
]
};
And I would like to access the data using these variable :
var part1name = "part1.name";
var part2quantity = "part2.qty";
var part3name1 = "part3[0].name";
part1name should be filled with someObject.part1.name
's value, which is "Part 1". Same thing with part2quantity which filled with 60.
Is there anyway to achieve this with either pure javascript or JQuery?
javascript jquery path nested
|
show 1 more comment
I have a data structure like this :
var someObject = {
'part1' : {
'name': 'Part 1',
'size': '20',
'qty' : '50'
},
'part2' : {
'name': 'Part 2',
'size': '15',
'qty' : '60'
},
'part3' : [
{
'name': 'Part 3A',
'size': '10',
'qty' : '20'
}, {
'name': 'Part 3B',
'size': '5',
'qty' : '20'
}, {
'name': 'Part 3C',
'size': '7.5',
'qty' : '20'
}
]
};
And I would like to access the data using these variable :
var part1name = "part1.name";
var part2quantity = "part2.qty";
var part3name1 = "part3[0].name";
part1name should be filled with someObject.part1.name
's value, which is "Part 1". Same thing with part2quantity which filled with 60.
Is there anyway to achieve this with either pure javascript or JQuery?
javascript jquery path nested
Not sure what you are asking here? You want to be able to query part1.name and have the text "part1.name" returned? Or you want a means to get the value stored within part1.name?
– BonyT
Jun 27 '11 at 10:27
have you tried doing likevar part1name = someObject.part1name;
`
– Rafay
Jun 27 '11 at 10:29
1
@BonyT : I want to query someObject.part1.name and return the value of it ("Part 1"). However, I want the query (I called it "the key") to be stored in a variable 'part1name'. Thanks for your reply. @3nigma : I have certainly do. But that is not my intention. Thanks for the reply.
– Komaruloh
Jun 27 '11 at 10:42
1
in the duplicate answer, i love fyr's answer stackoverflow.com/questions/8817394/…
– Steve Black
Mar 20 '13 at 2:09
1
See also Convert JavaScript string in dot notation into an object reference
– Bergi
Dec 15 '15 at 12:45
|
show 1 more comment
I have a data structure like this :
var someObject = {
'part1' : {
'name': 'Part 1',
'size': '20',
'qty' : '50'
},
'part2' : {
'name': 'Part 2',
'size': '15',
'qty' : '60'
},
'part3' : [
{
'name': 'Part 3A',
'size': '10',
'qty' : '20'
}, {
'name': 'Part 3B',
'size': '5',
'qty' : '20'
}, {
'name': 'Part 3C',
'size': '7.5',
'qty' : '20'
}
]
};
And I would like to access the data using these variable :
var part1name = "part1.name";
var part2quantity = "part2.qty";
var part3name1 = "part3[0].name";
part1name should be filled with someObject.part1.name
's value, which is "Part 1". Same thing with part2quantity which filled with 60.
Is there anyway to achieve this with either pure javascript or JQuery?
javascript jquery path nested
I have a data structure like this :
var someObject = {
'part1' : {
'name': 'Part 1',
'size': '20',
'qty' : '50'
},
'part2' : {
'name': 'Part 2',
'size': '15',
'qty' : '60'
},
'part3' : [
{
'name': 'Part 3A',
'size': '10',
'qty' : '20'
}, {
'name': 'Part 3B',
'size': '5',
'qty' : '20'
}, {
'name': 'Part 3C',
'size': '7.5',
'qty' : '20'
}
]
};
And I would like to access the data using these variable :
var part1name = "part1.name";
var part2quantity = "part2.qty";
var part3name1 = "part3[0].name";
part1name should be filled with someObject.part1.name
's value, which is "Part 1". Same thing with part2quantity which filled with 60.
Is there anyway to achieve this with either pure javascript or JQuery?
javascript jquery path nested
javascript jquery path nested
edited Aug 15 '17 at 16:57
Paul Roub
32.6k85773
32.6k85773
asked Jun 27 '11 at 10:25
KomarulohKomaruloh
1,8153107
1,8153107
Not sure what you are asking here? You want to be able to query part1.name and have the text "part1.name" returned? Or you want a means to get the value stored within part1.name?
– BonyT
Jun 27 '11 at 10:27
have you tried doing likevar part1name = someObject.part1name;
`
– Rafay
Jun 27 '11 at 10:29
1
@BonyT : I want to query someObject.part1.name and return the value of it ("Part 1"). However, I want the query (I called it "the key") to be stored in a variable 'part1name'. Thanks for your reply. @3nigma : I have certainly do. But that is not my intention. Thanks for the reply.
– Komaruloh
Jun 27 '11 at 10:42
1
in the duplicate answer, i love fyr's answer stackoverflow.com/questions/8817394/…
– Steve Black
Mar 20 '13 at 2:09
1
See also Convert JavaScript string in dot notation into an object reference
– Bergi
Dec 15 '15 at 12:45
|
show 1 more comment
Not sure what you are asking here? You want to be able to query part1.name and have the text "part1.name" returned? Or you want a means to get the value stored within part1.name?
– BonyT
Jun 27 '11 at 10:27
have you tried doing likevar part1name = someObject.part1name;
`
– Rafay
Jun 27 '11 at 10:29
1
@BonyT : I want to query someObject.part1.name and return the value of it ("Part 1"). However, I want the query (I called it "the key") to be stored in a variable 'part1name'. Thanks for your reply. @3nigma : I have certainly do. But that is not my intention. Thanks for the reply.
– Komaruloh
Jun 27 '11 at 10:42
1
in the duplicate answer, i love fyr's answer stackoverflow.com/questions/8817394/…
– Steve Black
Mar 20 '13 at 2:09
1
See also Convert JavaScript string in dot notation into an object reference
– Bergi
Dec 15 '15 at 12:45
Not sure what you are asking here? You want to be able to query part1.name and have the text "part1.name" returned? Or you want a means to get the value stored within part1.name?
– BonyT
Jun 27 '11 at 10:27
Not sure what you are asking here? You want to be able to query part1.name and have the text "part1.name" returned? Or you want a means to get the value stored within part1.name?
– BonyT
Jun 27 '11 at 10:27
have you tried doing like
var part1name = someObject.part1name;
`– Rafay
Jun 27 '11 at 10:29
have you tried doing like
var part1name = someObject.part1name;
`– Rafay
Jun 27 '11 at 10:29
1
1
@BonyT : I want to query someObject.part1.name and return the value of it ("Part 1"). However, I want the query (I called it "the key") to be stored in a variable 'part1name'. Thanks for your reply. @3nigma : I have certainly do. But that is not my intention. Thanks for the reply.
– Komaruloh
Jun 27 '11 at 10:42
@BonyT : I want to query someObject.part1.name and return the value of it ("Part 1"). However, I want the query (I called it "the key") to be stored in a variable 'part1name'. Thanks for your reply. @3nigma : I have certainly do. But that is not my intention. Thanks for the reply.
– Komaruloh
Jun 27 '11 at 10:42
1
1
in the duplicate answer, i love fyr's answer stackoverflow.com/questions/8817394/…
– Steve Black
Mar 20 '13 at 2:09
in the duplicate answer, i love fyr's answer stackoverflow.com/questions/8817394/…
– Steve Black
Mar 20 '13 at 2:09
1
1
See also Convert JavaScript string in dot notation into an object reference
– Bergi
Dec 15 '15 at 12:45
See also Convert JavaScript string in dot notation into an object reference
– Bergi
Dec 15 '15 at 12:45
|
show 1 more comment
29 Answers
29
active
oldest
votes
I just made this based on some similar code I already had, it appears to work:
Object.byString = function(o, s) {
s = s.replace(/[(w+)]/g, '.$1'); // convert indexes to properties
s = s.replace(/^./, ''); // strip a leading dot
var a = s.split('.');
for (var i = 0, n = a.length; i < n; ++i) {
var k = a[i];
if (k in o) {
o = o[k];
} else {
return;
}
}
return o;
}
Usage::
Object.byString(someObj, 'part3[0].name');
See a working demo at http://jsfiddle.net/alnitak/hEsys/
EDIT some have noticed that this code will throw an error if passed a string where the left-most indexes don't correspond to a correctly nested entry within the object. This is a valid concern, but IMHO best addressed with a try / catch
block when calling, rather than having this function silently return undefined
for an invalid index.
14
This works beautifully. Please contribute this to the internet by wrapping it as a node package.
– t3dodson
Jan 13 '15 at 22:38
9
@t3dodson I just did: github.com/capaj/object-resolve-path just be aware that this doesn't play nice when your property name contains '' in itself. Regex will replace it with '.' and it doesn't work as expected
– Capaj
Jul 30 '15 at 21:57
7
great stuff; using the lodash library, one can also do:_.get(object, nestedPropertyString);
– ian
Aug 13 '15 at 12:49
13
This will probably get lost in the sea of comments, however it errors if you try and address a property that doesn't exist. So'part3[0].name.iDontExist'
. Adding a check to see ifo
is an object in theif in
fixes the issue. (How you go about that is up-to you). See updated fiddle: jsfiddle.net/hEsys/418
– ste2425
Nov 17 '15 at 11:12
2
This is so gold. We have a config based application and this is kinda helpful! Thanks!
– Christian Esperar
Jun 22 '16 at 15:52
|
show 15 more comments
This is the solution I use:
function resolve(path, obj=self, separator='.') {
var properties = Array.isArray(path) ? path : path.split(separator)
return properties.reduce((prev, curr) => prev && prev[curr], obj)
}
Example usage:
// accessing property path on global scope
resolve("document.body.style.width")
// or
resolve("style.width", document.body)
// accessing array indexes
// (someObject has been defined in the question)
resolve("part3.0.size", someObject) // returns '10'
// accessing non-existent properties
// returns undefined when intermediate properties are not defined:
resolve('properties.that.do.not.exist', {hello:'world'})
// accessing properties with unusual keys by changing the separator
var obj = { object: { 'a.property.name.with.periods': 42 } }
resolve('object->a.property.name.with.periods', obj, '->') // returns 42
// accessing properties with unusual keys by passing a property name array
resolve(['object', 'a.property.name.with.periods'], obj) // returns 42
Limitations:
- Can't use brackets (
) for array indices—though specifying array indices between the separator token (e.g.,
.
) works fine as shown above.
7
using reduce is an excellent solution (one can also use_.reduce()
from the underscore or lodash library)
– Alp
May 22 '14 at 14:51
2
I thinkself
is probably undefined here. Do you meanthis
?
– Platinum Azure
Jun 17 '14 at 3:37
2
No,self
is defined.this
would be incorrect.
– speigg
Jun 18 '14 at 16:03
6
@PlatinumAzure developer.mozilla.org/en-US/docs/Web/API/Window.self
– Rahil Wazir
Nov 7 '14 at 10:15
1
Here's my complement to set values by path: pastebin.com/jDp5sKT9
– mroach
Jan 2 '17 at 8:42
|
show 6 more comments
This is now supported by lodash using _.get(obj, property)
. See https://lodash.com/docs#get
Example from the docs:
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.get(object, 'a[0].b.c');
// → 3
_.get(object, ['a', '0', 'b', 'c']);
// → 3
_.get(object, 'a.b.c', 'default');
// → 'default'
5
This should be the only accepted answer, because this is the only one working for both dot and bracket syntax and It doesn't fail, when we have '' in the string of a key in the path.
– Capaj
Aug 4 '15 at 2:12
5
This. Plus, it supports_.set(...)
– Josh C.
Aug 22 '17 at 6:23
what happes if the objet is not found?
– DDave
Oct 31 '17 at 16:58
@DDave if the value passed as the object is undefined or not an object,_.get
will show the same behavior as when no key is found in the provided object. eg_.get(null, "foo") -> undefined
,_.get(null, "foo", "bar") -> "bar"
. However this behavior is not defined in the docs so subject to change.
– Ian Walker-Sperber
Nov 2 '17 at 0:40
1
@Capaj you kiddin'? And who doesn't want/can't use lodash?
– Andre Figueiredo
Feb 19 '18 at 21:21
add a comment |
You'd have to parse the string yourself:
function getProperty(obj, prop) {
var parts = prop.split('.');
if (Array.isArray(parts)) {
var last = parts.pop(),
l = parts.length,
i = 1,
current = parts[0];
while((obj = obj[current]) && i < l) {
current = parts[i];
i++;
}
if(obj) {
return obj[last];
}
} else {
throw 'parts is not valid array';
}
}
This required that you also define array indexes with dot notation:
var part3name1 = "part3.0.name";
It makes the parsing easier.
DEMO
@Felix Kling : Your solution does provide me with what I need. And I thank you alot for that. But Alnitak also provide different ways and seem to work either. Since I can only choose one answer, I will choose Alnitak answer. Not that his solution is better than you or something like that. Anyway, I really appreciate your solution and effort you gave.
– Komaruloh
Jun 27 '11 at 11:25
1
@Komaruloh: Oh I thought you can always up vote answers on your own question.... anyway I was more or less kidding, I don't need more reputation ;) Happy coding!
– Felix Kling
Jun 27 '11 at 11:50
1
@Felix Kling : You need at least 15 reputation to up vote. :) I believe you don't need more reputation with 69k+ . Thanks
– Komaruloh
Jun 27 '11 at 14:58
@Felix FWIW - converting fromsyntax to property syntax is pretty trivial.
– Alnitak
Jun 27 '11 at 16:19
4
If you change the while loop towhile (l > 0 && (obj = obj[current]) && i < l)
then this code works for strings without dots as well.
– Snea
Aug 17 '14 at 6:18
|
show 2 more comments
Works for arrays / arrays inside the object also.
Defensive against invalid values.
/**
* Retrieve nested item from object/array
* @param {Object|Array} obj
* @param {String} path dot separated
* @param {*} def default value ( if result undefined )
* @returns {*}
*/
function path(obj, path, def){
var i, len;
for(i = 0,path = path.split('.'), len = path.length; i < len; i++){
if(!obj || typeof obj !== 'object') return def;
obj = obj[path[i]];
}
if(obj === undefined) return def;
return obj;
}
//////////////////////////
// TEST //
//////////////////////////
var arr = [true, {'sp ace': true}, true]
var obj = {
'sp ace': true,
arr: arr,
nested: {'dotted.str.ing': true},
arr3: arr
}
shouldThrow(`path(obj, "arr.0")`);
shouldBeDefined(`path(obj, "arr[0]")`);
shouldBeEqualToNumber(`path(obj, "arr.length")`, 3);
shouldBeTrue(`path(obj, "sp ace")`);
shouldBeEqualToString(`path(obj, "none.existed.prop", "fallback")`, "fallback");
shouldBeTrue(`path(obj, "nested['dotted.str.ing'])`);
<script src="https://cdn.rawgit.com/coderek/e7b30bac7634a50ad8fd/raw/174b6634c8f57aa8aac0716c5b7b2a7098e03584/js-test.js"></script>
9
Thanks this is the best and most performant answer - jsfiddle.net/Jw8XB/1
– Dominic
Jul 31 '13 at 23:00
@Endless, I'd like to emphasize the path should separate the items with dots. Braces won't work. I.e. to access first item in array use "0.sp ace".
– TheZver
Mar 27 '16 at 11:32
add a comment |
ES6: Only one line in Vanila JS (it return null if don't find instead of giving error):
'path.string'.split('.').reduce((p,c)=>p&&p[c]||null, MyOBJ)
or exemple:
'a.b.c'.split('.').reduce((p,c)=>p&&p[c]||null, {a:{b:{c:1}}})
For a ready to use function that also recognizes false, 0 and negative number and accept default values as parameter:
const resolvePath = (object, path, defaultValue) => path
.split('.')
.reduce((o, p) => o ? o[p] : defaultValue, object)
Exemple to use:
resolvePath(window,'document.body') => <body>
resolvePath(window,'document.body.xyz') => undefined
resolvePath(window,'document.body.xyz', null) => null
resolvePath(window,'document.body.xyz', 1) => 1
Bonus:
To set a path (Requested by @rob-gordon) you can use:
const setPath = (object, path, value) => path
.split('.')
.reduce((o,p) => o[p] = path.split('.').pop() === p ? value : o[p] || {}, object)
Example:
let myVar = {}
setPath(myVar, 'a.b.c', 42) => 42
console.log(myVar) => {a: {b: {c: 42}}}
Access array with :
const resolvePath = (object, path, defaultValue) => path
.split(/[.[]'"]/)
.filter(p => p)
.reduce((o, p) => o ? o[p] : defaultValue, object)
exemple
const myVar = {a:{b:[{c:1}]}}
resolvePath(myVar,'a.b[0].c') => 1
resolvePath(myVar,'a["b"]['0'].c') => 1
1
I love this technique. This is really messy but I wanted to use this technique for assignment.let o = {a:{b:{c:1}}}; let str = 'a.b.c'; str.split('.').splice(0, str.split('.').length - 1).reduce((p,c)=>p&&p[c]||null, o)[str.split('.').slice(-1)] = "some new value";
– rob-gordon
Jun 28 '17 at 17:15
1
I like the idea of using reduce but your logic seems off for0
,undefined
andnull
values.{a:{b:{c:0}}}
returnsnull
instead of0
. Perhaps explicitly checking for null or undefined will clear up these issues.(p,c)=>p === undefined || p === null ? undefined : p[c]
– SmujMaiku
Oct 15 '17 at 17:31
Hi @SmujMaiku, the "ready to use" function return correctly for '0', 'undefined' and 'null', I just tested on the console: resolvePath({a:{b:{c:0}}},'a.b.c',null) => 0; It check if the key exists instead of the value itself which avoid more than one check
– Adriano Spadoni
Oct 16 '17 at 9:18
here defaultValue did not work, usingReflect.has(o, k) ? ...
(ES6 Reflect.has) worked though
– Andre Figueiredo
Feb 23 '18 at 12:31
add a comment |
using eval:
var part1name = eval("someObject.part1.name");
wrap to return undefined on error
function path(obj, path) {
try {
return eval("obj." + path);
} catch(e) {
return undefined;
}
}
http://jsfiddle.net/shanimal/b3xTw/
Please use common sense and caution when wielding the power of eval. It's a bit like a light saber, if you turn it on there's a 90% chance you'll sever a limb. Its not for everybody.
5
Whether or not eval is a good idea depends on where the property string data is coming from. I doubt you have any reason to be concerned for hackers breaking in via a static "var p='a.b.c';eval(p);" type call. It's a perfectly fine idea for that.
– James Wilkins
Aug 21 '14 at 22:39
add a comment |
You can manage to obtain value of a deep object member with dot notation without any external JavaScript library with the simple following trick:
new Function('_', 'return _.' + path)(obj);
In your case to obtain value of part1.name
from someObject
just do:
new Function('_', 'return _.part1.name')(someObject);
Here is a simple fiddle demo: https://jsfiddle.net/harishanchu/oq5esowf/
2
function deep_value ( obj, path ) { return new Function( 'o', 'return o.' + path )( obj ); }
– ArcangelZith
Jul 29 '16 at 4:59
add a comment |
Here I offer more ways, which seem faster in many respects:
Option 1: Split string on . or [ or ] or ' or ", reverse it, skip empty items.
function getValue(path, origin) {
if (origin === void 0 || origin === null) origin = self ? self : this;
if (typeof path !== 'string') path = '' + path;
var parts = path.split(/[|]|.|'|"/g).reverse(), name; // (why reverse? because it's usually faster to pop off the end of an array)
while (parts.length) { name=parts.pop(); if (name) origin=origin[name]; }
return origin;
}
Option 2 (fastest of all, except eval
): Low level character scan (no regex/split/etc, just a quick char scan).
Note: This one does not support quotes for indexes.
function getValue(path, origin) {
if (origin === void 0 || origin === null) origin = self ? self : this;
if (typeof path !== 'string') path = '' + path;
var c = '', pc, i = 0, n = path.length, name = '';
if (n) while (i<=n) ((c = path[i++]) == '.' || c == '[' || c == ']' || c == void 0) ? (name?(origin = origin[name], name = ''):(pc=='.'||pc=='['||pc==']'&&c==']'?i=n+2:void 0),pc=c) : name += c;
if (i==n+2) throw "Invalid path: "+path;
return origin;
} // (around 1,000,000+/- ops/sec)
Option 3: (new: option 2 expanded to support quotes - a bit slower, but still fast)
function getValue(path, origin) {
if (origin === void 0 || origin === null) origin = self ? self : this;
if (typeof path !== 'string') path = '' + path;
var c, pc, i = 0, n = path.length, name = '', q;
while (i<=n)
((c = path[i++]) == '.' || c == '[' || c == ']' || c == "'" || c == '"' || c == void 0) ? (c==q&&path[i]==']'?q='':q?name+=c:name?(origin?origin=origin[name]:i=n+2,name='') : (pc=='['&&(c=='"'||c=="'")?q=c:pc=='.'||pc=='['||pc==']'&&c==']'||pc=='"'||pc=="'"?i=n+2:void 0), pc=c) : name += c;
if (i==n+2 || name) throw "Invalid path: "+path;
return origin;
}
JSPerf: http://jsperf.com/ways-to-dereference-a-delimited-property-string/3
"eval(...)" is still king though (performance wise that is). If you have property paths directly under your control, there shouldn't be any issues with using 'eval' (especially if speed is desired). If pulling property paths "over the wire" (on the line!? lol :P), then yes, use something else to be safe. Only an idiot would say to never use "eval" at all, as there ARE good reasons when to use it. Also, "It is used in Doug Crockford's JSON parser." If the input is safe, then no problems at all. Use the right tool for the right job, that's it.
add a comment |
This will probably never see the light of day... but here it is anyway.
- Replace
bracket syntax with
.
- Split on
.
character - Remove blank strings
- Find the path (otherwise
undefined
)
// "one liner" (ES6)
const deep_value = (obj, path) =>
path
.replace(/[|].?/g, '.')
.split('.')
.filter(s => s)
.reduce((acc, val) => acc && acc[val], obj);
// ... and that's it.
var someObject = {
'part1' : {
'name': 'Part 1',
'size': '20',
'qty' : '50'
},
'part2' : {
'name': 'Part 2',
'size': '15',
'qty' : '60'
},
'part3' : [
{
'name': 'Part 3A',
'size': '10',
'qty' : '20'
}
// ...
]
};
console.log(deep_value(someObject, "part1.name")); // Part 1
console.log(deep_value(someObject, "part2.qty")); // 60
console.log(deep_value(someObject, "part3[0].name")); // Part 3A
1
It did see the light of the day!! thanks
– abann sunny
Jan 15 at 21:01
add a comment |
I think you are asking for this:
var part1name = someObject.part1.name;
var part2quantity = someObject.part2.qty;
var part3name1 = someObject.part3[0].name;
You could be asking for this:
var part1name = someObject["part1"]["name"];
var part2quantity = someObject["part2"]["qty"];
var part3name1 = someObject["part3"][0]["name"];
Both of which will work
Or maybe you are asking for this
var partName = "part1";
var nameStr = "name";
var part1name = someObject[partName][nameStr];
Finally you could be asking for this
var partName = "part1.name";
var partBits = partName.split(".");
var part1name = someObject[partBits[0]][partBits[1]];
I think OP's asking for the last solution. However, strings don't haveSplit
method, but rathersplit
.
– duri
Jun 27 '11 at 10:37
Actualy I was asking the last one. The partName variable is filled with string indicating the key-structure to value. Your solution seems makes sense. However I may need to modify for extended depth in the data, like 4-5 level and more. And I am wondering if I can treat the array and object uniformly with this?
– Komaruloh
Jun 27 '11 at 10:38
add a comment |
Speigg's approach is very neat and clean, though I found this reply while searching for the solution of accessing AngularJS $scope properties by string path and with a little modification it does the job:
$scope.resolve = function( path, obj ) {
return path.split('.').reduce( function( prev, curr ) {
return prev[curr];
}, obj || this );
}
Just place this function in your root controller and use it any child scope like this:
$scope.resolve( 'path.to.any.object.in.scope')
add a comment |
It's a one liner with lodash.
const deep = { l1: { l2: { l3: "Hello" } } };
const prop = "l1.l2.l3";
const val = _.reduce(prop.split('.'), function(result, value) { return result ? result[value] : undefined; }, deep);
// val === "Hello"
Or even better...
const val = _.get(deep, prop);
Or ES6 version w/ reduce...
const val = prop.split('.').reduce((r, val) => { return r ? r[val] : undefined; }, deep);
Plunkr
add a comment |
I haven't yet found a package to do all of the operations with a string path, so I ended up writing my own quick little package which supports insert(), get() (with default return), set() and remove() operations.
You can use dot notation, brackets, number indices, string number properties, and keys with non-word characters. Simple usage below:
> var jsocrud = require('jsocrud');
...
// Get (Read) ---
> var obj = {
> foo: [
> {
> 'key w/ non-word chars': 'bar'
> }
> ]
> };
undefined
> jsocrud.get(obj, '.foo[0]["key w/ non-word chars"]');
'bar'
https://www.npmjs.com/package/jsocrud
https://github.com/vertical-knowledge/jsocrud
add a comment |
Simple function, allowing for either a string or array path.
function get(obj, path) {
if(typeof path === 'string') path = path.split('.');
if(path.length === 0) return obj;
return get(obj[path[0]], path.slice(1));
}
const obj = {a: {b: {c: 'foo'}}};
console.log(get(obj, 'a.b.c')); //foo
OR
console.log(get(obj, ['a', 'b', 'c'])); //foo
If you're going to post code as an answer, please explain why the code answers the question.
– Tieson T.
Dec 26 '16 at 5:44
add a comment |
Just in case, anyone's visiting this question in 2017 or later and looking for an easy-to-remember way, here's an elaborate blog post on Accessing Nested Objects in JavaScript without being bamboozled by
Cannot read property 'foo' of undefined error
Access Nested Objects Using Array Reduce
Let's take this example structure
const user = {
id: 101,
email: 'jack@dev.com',
personalInfo: {
name: 'Jack',
address: [{
line1: 'westwish st',
line2: 'washmasher',
city: 'wallas',
state: 'WX'
}]
}
}
To be able to access nested arrays, you can write your own array reduce util.
const getNestedObject = (nestedObj, pathArr) => {
return pathArr.reduce((obj, key) =>
(obj && obj[key] !== 'undefined') ? obj[key] : undefined, nestedObj);
}
// pass in your object structure as array elements
const name = getNestedObject(user, ['personalInfo', 'name']);
// to access nested array, just pass in array index as an element the path array.
const city = getNestedObject(user, ['personalInfo', 'address', 0, 'city']);
// this will return the city from the first address item.
There is also an excellent type handling minimal library typy that does all this for you.
With typy, your code will look like this
const city = t(user, 'personalInfo.address[0].city').safeObject;
Disclaimer: I am the author of this package.
add a comment |
There is an npm
module now for doing this: https://github.com/erictrinh/safe-access
Example usage:
var access = require('safe-access');
access(very, 'nested.property.and.array[0]');
add a comment |
/**
* Access a deep value inside a object
* Works by passing a path like "foo.bar", also works with nested arrays like "foo[0][1].baz"
* @author Victor B. https://gist.github.com/victornpb/4c7882c1b9d36292308e
* Unit tests: http://jsfiddle.net/Victornpb/0u1qygrh/
*/
function getDeepVal(obj, path) {
if (typeof obj === "undefined" || obj === null) return;
path = path.split(/[.[]"']{1,2}/);
for (var i = 0, l = path.length; i < l; i++) {
if (path[i] === "") continue;
obj = obj[path[i]];
if (typeof obj === "undefined" || obj === null) return;
}
return obj;
}
Works with
getDeepVal(obj,'foo.bar')
getDeepVal(obj,'foo.1.bar')
getDeepVal(obj,'foo[0].baz')
getDeepVal(obj,'foo[1][2]')
getDeepVal(obj,"foo['bar'].baz")
getDeepVal(obj,"foo['bar']['baz']")
getDeepVal(obj,"foo.bar.0.baz[1]['2']['w'].aaa["f"].bb")
add a comment |
While reduce is good, I am surprised no one used forEach:
function valueForKeyPath(obj, path){
const keys = path.split('.');
keys.forEach((key)=> obj = obj[key]);
return obj;
};
Test
You are not even checking if obj[key] actually exists. It's unreliable.
– Carles Alcolea
Jul 22 '18 at 4:08
@CarlesAlcolea by default js will neither check if the key of an object exists:a.b.c
will raise an exception if there is no propertyb
in your object. If you need something silently dismissing the wrong keypath (which I do not recommend), you can still replace the forEach with this onekeys.forEach((key)=> obj = (obj||{})[key]);
– Flavien Volken
Jul 23 '18 at 7:57
I run through it an object that was missing a curly brace, my bad :)
– Carles Alcolea
Jul 28 '18 at 23:59
add a comment |
If you need to access different nested key without knowing it at coding time (it will be trivial to address them) you can use the array notation accessor:
var part1name = someObject['part1']['name'];
var part2quantity = someObject['part2']['qty'];
var part3name1 = someObject['part3'][0]['name'];
They are equivalent to the dot notation accessor and may vary at runtime, for example:
var part = 'part1';
var property = 'name';
var part1name = someObject[part][property];
is equivalent to
var part1name = someObject['part1']['name'];
or
var part1name = someObject.part1.name;
I hope this address your question...
EDIT
I won't use a string to mantain a sort of xpath query to access an object value.
As you have to call a function to parse the query and retrieve the value I would follow another path (not :
var part1name = function(){ return this.part1.name; }
var part2quantity = function() { return this['part2']['qty']; }
var part3name1 = function() { return this.part3[0]['name'];}
// usage: part1name.apply(someObject);
or, if you are uneasy with the apply method
var part1name = function(obj){ return obj.part1.name; }
var part2quantity = function(obj) { return obj['part2']['qty']; }
var part3name1 = function(obj) { return obj.part3[0]['name'];}
// usage: part1name(someObject);
The functions are shorter, clearer, the interpreter check them for you for syntax errors and so on.
By the way, I feel that a simple assignment made at right time will be sufficent...
Interesting. But in my case, the someObject is initialize yet when I assign value to part1name. I only know the structure. That is why I use string to describe the structure. And hoping to be able to use it to query my data from someObject. Thanks for sharing your thought. :)
– Komaruloh
Jun 27 '11 at 10:47
@Komaruloh : I think you would write that the object is NOT initialized yet when you create your variables. By the way I don't get the point, why can't you do the assignment at appropriate time?
– Eineki
Jun 27 '11 at 11:24
Sorry about not mentioning that someObject is not initialized yet. As for the reason, someObject is fetch via web service. And I want to have an array of header which consist of part1name, part2qty, etc. So that I could just loop through the header array and get the value I wanted based on part1name value as the 'key'/path to someObject.
– Komaruloh
Jun 27 '11 at 11:47
add a comment |
Just had the same question recently and successfully used https://npmjs.org/package/tea-properties which also set
nested object/arrays :
get:
var o = {
prop: {
arr: [
{foo: 'bar'}
]
}
};
var properties = require('tea-properties');
var value = properties.get(o, 'prop.arr[0].foo');
assert(value, 'bar'); // true
set:
var o = {};
var properties = require('tea-properties');
properties.set(o, 'prop.arr[0].foo', 'bar');
assert(o.prop.arr[0].foo, 'bar'); // true
"This module has been discontinued. Use chaijs/pathval."
– Patrick Fisher
Mar 18 '14 at 0:09
add a comment |
The solutions here are just for accessing the deeply nested keys. I needed one for accessing, adding, modifying and deleting the keys. This is what I came up with:
var deepAccessObject = function(object, path_to_key, type_of_function, value){
switch(type_of_function){
//Add key/modify key
case 0:
if(path_to_key.length === 1){
if(value)
object[path_to_key[0]] = value;
return object[path_to_key[0]];
}else{
if(object[path_to_key[0]])
return deepAccessObject(object[path_to_key[0]], path_to_key.slice(1), type_of_function, value);
else
object[path_to_key[0]] = {};
}
break;
//delete key
case 1:
if(path_to_key.length === 1){
delete object[path_to_key[0]];
return true;
}else{
if(object[path_to_key[0]])
return deepAccessObject(object[path_to_key[0]], path_to_key.slice(1), type_of_function, value);
else
return false;
}
break;
default:
console.log("Wrong type of function");
}
};
path_to_key
: path in an array. You can replace it by yourstring_path.split(".")
.
type_of_function
: 0 for accessing(dont pass any value tovalue
), 0 for add and modify. 1 for delete.
add a comment |
Instead of a string an array can be used adressing nested objects and arrays e.g.: ["my_field", "another_field", 0, "last_field", 10]
Here is an example that would change a field based on this array representation. I am using something like that in react.js for controlled input fields that change the state of nested structures.
let state = {
test: "test_value",
nested: {
level1: "level1 value"
},
arr: [1, 2, 3],
nested_arr: {
arr: ["buh", "bah", "foo"]
}
}
function handleChange(value, fields) {
let update_field = state;
for(var i = 0; i < fields.length - 1; i++){
update_field = update_field[fields[i]];
}
update_field[fields[fields.length-1]] = value;
}
handleChange("update", ["test"]);
handleChange("update_nested", ["nested","level1"]);
handleChange(100, ["arr",0]);
handleChange('changed_foo', ["nested_arr", "arr", 3]);
console.log(state);
add a comment |
Based on a previous answer, I have created a function that can also handle brackets. But no dots inside them due to the split.
function get(obj, str) {
return str.split(/.|[/g).map(function(crumb) {
return crumb.replace(/]$/, '').trim().replace(/^(["'])((?:(?!1)[^\]|\.)*?)1$/, (match, quote, str) => str.replace(/\(\)?/g, "$1"));
}).reduce(function(obj, prop) {
return obj ? obj[prop] : undefined;
}, obj);
}
add a comment |
// (IE9+) Two steps
var pathString = "[0]['property'].others[3].next['final']";
var obj = [{
property: {
others: [1, 2, 3, {
next: {
final: "SUCCESS"
}
}]
}
}];
// Turn string to path array
var pathArray = pathString
.replace(/[["']?([w]+)["']?]/g,".$1")
.split(".")
.splice(1);
// Add object prototype method
Object.prototype.path = function (path) {
try {
return [this].concat(path).reduce(function (f, l) {
return f[l];
});
} catch (e) {
console.error(e);
}
};
// usage
console.log(obj.path(pathArray));
console.log(obj.path([0,"doesNotExist"]));
add a comment |
Working with Underscore
's property
or propertyOf
:
var test = {
foo: {
bar: {
baz: 'hello'
}
}
}
var string = 'foo.bar.baz';
// document.write(_.propertyOf(test)(string.split('.')))
document.write(_.property(string.split('.'))(test));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
Good Luck...
add a comment |
Inspired by @webjay's answer:
https://stackoverflow.com/a/46008856/4110122
I made this function which can you use it to Get/ Set/ Unset any value in object
function Object_Manager(obj, Path, value, Action)
{
try
{
if(Array.isArray(Path) == false)
{
Path = [Path];
}
let level = 0;
var Return_Value;
Path.reduce((a, b)=>{
level++;
if (level === Path.length)
{
if(Action === 'Set')
{
a[b] = value;
return value;
}
else if(Action === 'Get')
{
Return_Value = a[b];
}
else if(Action === 'Unset')
{
delete a[b];
}
}
else
{
return a[b];
}
}, obj);
return Return_Value;
}
catch(err)
{
console.error(err);
return obj;
}
}
To use it:
// Set
Object_Manager(Obj,[Level1,Level2,Level3],New_Value, 'Set');
// Get
Object_Manager(Obj,[Level1,Level2,Level3],'', 'Get');
// Unset
Object_Manager(Obj,[Level1,Level2,Level3],'', 'Unset');
add a comment |
What about this solution:
setJsonValue: function (json, field, val) {
if (field !== undefined){
try {
eval("json." + field + " = val");
}
catch(e){
;
}
}
}
And this one, for getting:
getJsonValue: function (json, field){
var value = undefined;
if (field !== undefined) {
try {
eval("value = json." + field);
}
catch(e){
;
}
}
return value;
};
Probably some will consider them unsafe, but they must be much faster then, parsing the string.
add a comment |
Building off of Alnitak's answer:
if(!Object.prototype.byString){
//NEW byString which can update values
Object.prototype.byString = function(s, v, o) {
var _o = o || this;
s = s.replace(/[(w+)]/g, '.$1'); // CONVERT INDEXES TO PROPERTIES
s = s.replace(/^./, ''); // STRIP A LEADING DOT
var a = s.split('.'); //ARRAY OF STRINGS SPLIT BY '.'
for (var i = 0; i < a.length; ++i) {//LOOP OVER ARRAY OF STRINGS
var k = a[i];
if (k in _o) {//LOOP THROUGH OBJECT KEYS
if(_o.hasOwnProperty(k)){//USE ONLY KEYS WE CREATED
if(v !== undefined){//IF WE HAVE A NEW VALUE PARAM
if(i === a.length -1){//IF IT'S THE LAST IN THE ARRAY
_o[k] = v;
}
}
_o = _o[k];//NO NEW VALUE SO JUST RETURN THE CURRENT VALUE
}
} else {
return;
}
}
return _o;
};
}
This allows you to set a value as well!
I've created an npm package and github with this as well
add a comment |
protected by Samuel Liew♦ Oct 5 '15 at 9:21
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
29 Answers
29
active
oldest
votes
29 Answers
29
active
oldest
votes
active
oldest
votes
active
oldest
votes
I just made this based on some similar code I already had, it appears to work:
Object.byString = function(o, s) {
s = s.replace(/[(w+)]/g, '.$1'); // convert indexes to properties
s = s.replace(/^./, ''); // strip a leading dot
var a = s.split('.');
for (var i = 0, n = a.length; i < n; ++i) {
var k = a[i];
if (k in o) {
o = o[k];
} else {
return;
}
}
return o;
}
Usage::
Object.byString(someObj, 'part3[0].name');
See a working demo at http://jsfiddle.net/alnitak/hEsys/
EDIT some have noticed that this code will throw an error if passed a string where the left-most indexes don't correspond to a correctly nested entry within the object. This is a valid concern, but IMHO best addressed with a try / catch
block when calling, rather than having this function silently return undefined
for an invalid index.
14
This works beautifully. Please contribute this to the internet by wrapping it as a node package.
– t3dodson
Jan 13 '15 at 22:38
9
@t3dodson I just did: github.com/capaj/object-resolve-path just be aware that this doesn't play nice when your property name contains '' in itself. Regex will replace it with '.' and it doesn't work as expected
– Capaj
Jul 30 '15 at 21:57
7
great stuff; using the lodash library, one can also do:_.get(object, nestedPropertyString);
– ian
Aug 13 '15 at 12:49
13
This will probably get lost in the sea of comments, however it errors if you try and address a property that doesn't exist. So'part3[0].name.iDontExist'
. Adding a check to see ifo
is an object in theif in
fixes the issue. (How you go about that is up-to you). See updated fiddle: jsfiddle.net/hEsys/418
– ste2425
Nov 17 '15 at 11:12
2
This is so gold. We have a config based application and this is kinda helpful! Thanks!
– Christian Esperar
Jun 22 '16 at 15:52
|
show 15 more comments
I just made this based on some similar code I already had, it appears to work:
Object.byString = function(o, s) {
s = s.replace(/[(w+)]/g, '.$1'); // convert indexes to properties
s = s.replace(/^./, ''); // strip a leading dot
var a = s.split('.');
for (var i = 0, n = a.length; i < n; ++i) {
var k = a[i];
if (k in o) {
o = o[k];
} else {
return;
}
}
return o;
}
Usage::
Object.byString(someObj, 'part3[0].name');
See a working demo at http://jsfiddle.net/alnitak/hEsys/
EDIT some have noticed that this code will throw an error if passed a string where the left-most indexes don't correspond to a correctly nested entry within the object. This is a valid concern, but IMHO best addressed with a try / catch
block when calling, rather than having this function silently return undefined
for an invalid index.
14
This works beautifully. Please contribute this to the internet by wrapping it as a node package.
– t3dodson
Jan 13 '15 at 22:38
9
@t3dodson I just did: github.com/capaj/object-resolve-path just be aware that this doesn't play nice when your property name contains '' in itself. Regex will replace it with '.' and it doesn't work as expected
– Capaj
Jul 30 '15 at 21:57
7
great stuff; using the lodash library, one can also do:_.get(object, nestedPropertyString);
– ian
Aug 13 '15 at 12:49
13
This will probably get lost in the sea of comments, however it errors if you try and address a property that doesn't exist. So'part3[0].name.iDontExist'
. Adding a check to see ifo
is an object in theif in
fixes the issue. (How you go about that is up-to you). See updated fiddle: jsfiddle.net/hEsys/418
– ste2425
Nov 17 '15 at 11:12
2
This is so gold. We have a config based application and this is kinda helpful! Thanks!
– Christian Esperar
Jun 22 '16 at 15:52
|
show 15 more comments
I just made this based on some similar code I already had, it appears to work:
Object.byString = function(o, s) {
s = s.replace(/[(w+)]/g, '.$1'); // convert indexes to properties
s = s.replace(/^./, ''); // strip a leading dot
var a = s.split('.');
for (var i = 0, n = a.length; i < n; ++i) {
var k = a[i];
if (k in o) {
o = o[k];
} else {
return;
}
}
return o;
}
Usage::
Object.byString(someObj, 'part3[0].name');
See a working demo at http://jsfiddle.net/alnitak/hEsys/
EDIT some have noticed that this code will throw an error if passed a string where the left-most indexes don't correspond to a correctly nested entry within the object. This is a valid concern, but IMHO best addressed with a try / catch
block when calling, rather than having this function silently return undefined
for an invalid index.
I just made this based on some similar code I already had, it appears to work:
Object.byString = function(o, s) {
s = s.replace(/[(w+)]/g, '.$1'); // convert indexes to properties
s = s.replace(/^./, ''); // strip a leading dot
var a = s.split('.');
for (var i = 0, n = a.length; i < n; ++i) {
var k = a[i];
if (k in o) {
o = o[k];
} else {
return;
}
}
return o;
}
Usage::
Object.byString(someObj, 'part3[0].name');
See a working demo at http://jsfiddle.net/alnitak/hEsys/
EDIT some have noticed that this code will throw an error if passed a string where the left-most indexes don't correspond to a correctly nested entry within the object. This is a valid concern, but IMHO best addressed with a try / catch
block when calling, rather than having this function silently return undefined
for an invalid index.
edited Oct 10 '16 at 13:40
answered Jun 27 '11 at 10:40
AlnitakAlnitak
270k62341432
270k62341432
14
This works beautifully. Please contribute this to the internet by wrapping it as a node package.
– t3dodson
Jan 13 '15 at 22:38
9
@t3dodson I just did: github.com/capaj/object-resolve-path just be aware that this doesn't play nice when your property name contains '' in itself. Regex will replace it with '.' and it doesn't work as expected
– Capaj
Jul 30 '15 at 21:57
7
great stuff; using the lodash library, one can also do:_.get(object, nestedPropertyString);
– ian
Aug 13 '15 at 12:49
13
This will probably get lost in the sea of comments, however it errors if you try and address a property that doesn't exist. So'part3[0].name.iDontExist'
. Adding a check to see ifo
is an object in theif in
fixes the issue. (How you go about that is up-to you). See updated fiddle: jsfiddle.net/hEsys/418
– ste2425
Nov 17 '15 at 11:12
2
This is so gold. We have a config based application and this is kinda helpful! Thanks!
– Christian Esperar
Jun 22 '16 at 15:52
|
show 15 more comments
14
This works beautifully. Please contribute this to the internet by wrapping it as a node package.
– t3dodson
Jan 13 '15 at 22:38
9
@t3dodson I just did: github.com/capaj/object-resolve-path just be aware that this doesn't play nice when your property name contains '' in itself. Regex will replace it with '.' and it doesn't work as expected
– Capaj
Jul 30 '15 at 21:57
7
great stuff; using the lodash library, one can also do:_.get(object, nestedPropertyString);
– ian
Aug 13 '15 at 12:49
13
This will probably get lost in the sea of comments, however it errors if you try and address a property that doesn't exist. So'part3[0].name.iDontExist'
. Adding a check to see ifo
is an object in theif in
fixes the issue. (How you go about that is up-to you). See updated fiddle: jsfiddle.net/hEsys/418
– ste2425
Nov 17 '15 at 11:12
2
This is so gold. We have a config based application and this is kinda helpful! Thanks!
– Christian Esperar
Jun 22 '16 at 15:52
14
14
This works beautifully. Please contribute this to the internet by wrapping it as a node package.
– t3dodson
Jan 13 '15 at 22:38
This works beautifully. Please contribute this to the internet by wrapping it as a node package.
– t3dodson
Jan 13 '15 at 22:38
9
9
@t3dodson I just did: github.com/capaj/object-resolve-path just be aware that this doesn't play nice when your property name contains '' in itself. Regex will replace it with '.' and it doesn't work as expected
– Capaj
Jul 30 '15 at 21:57
@t3dodson I just did: github.com/capaj/object-resolve-path just be aware that this doesn't play nice when your property name contains '' in itself. Regex will replace it with '.' and it doesn't work as expected
– Capaj
Jul 30 '15 at 21:57
7
7
great stuff; using the lodash library, one can also do:
_.get(object, nestedPropertyString);
– ian
Aug 13 '15 at 12:49
great stuff; using the lodash library, one can also do:
_.get(object, nestedPropertyString);
– ian
Aug 13 '15 at 12:49
13
13
This will probably get lost in the sea of comments, however it errors if you try and address a property that doesn't exist. So
'part3[0].name.iDontExist'
. Adding a check to see if o
is an object in the if in
fixes the issue. (How you go about that is up-to you). See updated fiddle: jsfiddle.net/hEsys/418– ste2425
Nov 17 '15 at 11:12
This will probably get lost in the sea of comments, however it errors if you try and address a property that doesn't exist. So
'part3[0].name.iDontExist'
. Adding a check to see if o
is an object in the if in
fixes the issue. (How you go about that is up-to you). See updated fiddle: jsfiddle.net/hEsys/418– ste2425
Nov 17 '15 at 11:12
2
2
This is so gold. We have a config based application and this is kinda helpful! Thanks!
– Christian Esperar
Jun 22 '16 at 15:52
This is so gold. We have a config based application and this is kinda helpful! Thanks!
– Christian Esperar
Jun 22 '16 at 15:52
|
show 15 more comments
This is the solution I use:
function resolve(path, obj=self, separator='.') {
var properties = Array.isArray(path) ? path : path.split(separator)
return properties.reduce((prev, curr) => prev && prev[curr], obj)
}
Example usage:
// accessing property path on global scope
resolve("document.body.style.width")
// or
resolve("style.width", document.body)
// accessing array indexes
// (someObject has been defined in the question)
resolve("part3.0.size", someObject) // returns '10'
// accessing non-existent properties
// returns undefined when intermediate properties are not defined:
resolve('properties.that.do.not.exist', {hello:'world'})
// accessing properties with unusual keys by changing the separator
var obj = { object: { 'a.property.name.with.periods': 42 } }
resolve('object->a.property.name.with.periods', obj, '->') // returns 42
// accessing properties with unusual keys by passing a property name array
resolve(['object', 'a.property.name.with.periods'], obj) // returns 42
Limitations:
- Can't use brackets (
) for array indices—though specifying array indices between the separator token (e.g.,
.
) works fine as shown above.
7
using reduce is an excellent solution (one can also use_.reduce()
from the underscore or lodash library)
– Alp
May 22 '14 at 14:51
2
I thinkself
is probably undefined here. Do you meanthis
?
– Platinum Azure
Jun 17 '14 at 3:37
2
No,self
is defined.this
would be incorrect.
– speigg
Jun 18 '14 at 16:03
6
@PlatinumAzure developer.mozilla.org/en-US/docs/Web/API/Window.self
– Rahil Wazir
Nov 7 '14 at 10:15
1
Here's my complement to set values by path: pastebin.com/jDp5sKT9
– mroach
Jan 2 '17 at 8:42
|
show 6 more comments
This is the solution I use:
function resolve(path, obj=self, separator='.') {
var properties = Array.isArray(path) ? path : path.split(separator)
return properties.reduce((prev, curr) => prev && prev[curr], obj)
}
Example usage:
// accessing property path on global scope
resolve("document.body.style.width")
// or
resolve("style.width", document.body)
// accessing array indexes
// (someObject has been defined in the question)
resolve("part3.0.size", someObject) // returns '10'
// accessing non-existent properties
// returns undefined when intermediate properties are not defined:
resolve('properties.that.do.not.exist', {hello:'world'})
// accessing properties with unusual keys by changing the separator
var obj = { object: { 'a.property.name.with.periods': 42 } }
resolve('object->a.property.name.with.periods', obj, '->') // returns 42
// accessing properties with unusual keys by passing a property name array
resolve(['object', 'a.property.name.with.periods'], obj) // returns 42
Limitations:
- Can't use brackets (
) for array indices—though specifying array indices between the separator token (e.g.,
.
) works fine as shown above.
7
using reduce is an excellent solution (one can also use_.reduce()
from the underscore or lodash library)
– Alp
May 22 '14 at 14:51
2
I thinkself
is probably undefined here. Do you meanthis
?
– Platinum Azure
Jun 17 '14 at 3:37
2
No,self
is defined.this
would be incorrect.
– speigg
Jun 18 '14 at 16:03
6
@PlatinumAzure developer.mozilla.org/en-US/docs/Web/API/Window.self
– Rahil Wazir
Nov 7 '14 at 10:15
1
Here's my complement to set values by path: pastebin.com/jDp5sKT9
– mroach
Jan 2 '17 at 8:42
|
show 6 more comments
This is the solution I use:
function resolve(path, obj=self, separator='.') {
var properties = Array.isArray(path) ? path : path.split(separator)
return properties.reduce((prev, curr) => prev && prev[curr], obj)
}
Example usage:
// accessing property path on global scope
resolve("document.body.style.width")
// or
resolve("style.width", document.body)
// accessing array indexes
// (someObject has been defined in the question)
resolve("part3.0.size", someObject) // returns '10'
// accessing non-existent properties
// returns undefined when intermediate properties are not defined:
resolve('properties.that.do.not.exist', {hello:'world'})
// accessing properties with unusual keys by changing the separator
var obj = { object: { 'a.property.name.with.periods': 42 } }
resolve('object->a.property.name.with.periods', obj, '->') // returns 42
// accessing properties with unusual keys by passing a property name array
resolve(['object', 'a.property.name.with.periods'], obj) // returns 42
Limitations:
- Can't use brackets (
) for array indices—though specifying array indices between the separator token (e.g.,
.
) works fine as shown above.
This is the solution I use:
function resolve(path, obj=self, separator='.') {
var properties = Array.isArray(path) ? path : path.split(separator)
return properties.reduce((prev, curr) => prev && prev[curr], obj)
}
Example usage:
// accessing property path on global scope
resolve("document.body.style.width")
// or
resolve("style.width", document.body)
// accessing array indexes
// (someObject has been defined in the question)
resolve("part3.0.size", someObject) // returns '10'
// accessing non-existent properties
// returns undefined when intermediate properties are not defined:
resolve('properties.that.do.not.exist', {hello:'world'})
// accessing properties with unusual keys by changing the separator
var obj = { object: { 'a.property.name.with.periods': 42 } }
resolve('object->a.property.name.with.periods', obj, '->') // returns 42
// accessing properties with unusual keys by passing a property name array
resolve(['object', 'a.property.name.with.periods'], obj) // returns 42
Limitations:
- Can't use brackets (
) for array indices—though specifying array indices between the separator token (e.g.,
.
) works fine as shown above.
edited Aug 15 '18 at 0:59
answered Mar 2 '14 at 16:06
speiggspeigg
1,420195
1,420195
7
using reduce is an excellent solution (one can also use_.reduce()
from the underscore or lodash library)
– Alp
May 22 '14 at 14:51
2
I thinkself
is probably undefined here. Do you meanthis
?
– Platinum Azure
Jun 17 '14 at 3:37
2
No,self
is defined.this
would be incorrect.
– speigg
Jun 18 '14 at 16:03
6
@PlatinumAzure developer.mozilla.org/en-US/docs/Web/API/Window.self
– Rahil Wazir
Nov 7 '14 at 10:15
1
Here's my complement to set values by path: pastebin.com/jDp5sKT9
– mroach
Jan 2 '17 at 8:42
|
show 6 more comments
7
using reduce is an excellent solution (one can also use_.reduce()
from the underscore or lodash library)
– Alp
May 22 '14 at 14:51
2
I thinkself
is probably undefined here. Do you meanthis
?
– Platinum Azure
Jun 17 '14 at 3:37
2
No,self
is defined.this
would be incorrect.
– speigg
Jun 18 '14 at 16:03
6
@PlatinumAzure developer.mozilla.org/en-US/docs/Web/API/Window.self
– Rahil Wazir
Nov 7 '14 at 10:15
1
Here's my complement to set values by path: pastebin.com/jDp5sKT9
– mroach
Jan 2 '17 at 8:42
7
7
using reduce is an excellent solution (one can also use
_.reduce()
from the underscore or lodash library)– Alp
May 22 '14 at 14:51
using reduce is an excellent solution (one can also use
_.reduce()
from the underscore or lodash library)– Alp
May 22 '14 at 14:51
2
2
I think
self
is probably undefined here. Do you mean this
?– Platinum Azure
Jun 17 '14 at 3:37
I think
self
is probably undefined here. Do you mean this
?– Platinum Azure
Jun 17 '14 at 3:37
2
2
No,
self
is defined. this
would be incorrect.– speigg
Jun 18 '14 at 16:03
No,
self
is defined. this
would be incorrect.– speigg
Jun 18 '14 at 16:03
6
6
@PlatinumAzure developer.mozilla.org/en-US/docs/Web/API/Window.self
– Rahil Wazir
Nov 7 '14 at 10:15
@PlatinumAzure developer.mozilla.org/en-US/docs/Web/API/Window.self
– Rahil Wazir
Nov 7 '14 at 10:15
1
1
Here's my complement to set values by path: pastebin.com/jDp5sKT9
– mroach
Jan 2 '17 at 8:42
Here's my complement to set values by path: pastebin.com/jDp5sKT9
– mroach
Jan 2 '17 at 8:42
|
show 6 more comments
This is now supported by lodash using _.get(obj, property)
. See https://lodash.com/docs#get
Example from the docs:
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.get(object, 'a[0].b.c');
// → 3
_.get(object, ['a', '0', 'b', 'c']);
// → 3
_.get(object, 'a.b.c', 'default');
// → 'default'
5
This should be the only accepted answer, because this is the only one working for both dot and bracket syntax and It doesn't fail, when we have '' in the string of a key in the path.
– Capaj
Aug 4 '15 at 2:12
5
This. Plus, it supports_.set(...)
– Josh C.
Aug 22 '17 at 6:23
what happes if the objet is not found?
– DDave
Oct 31 '17 at 16:58
@DDave if the value passed as the object is undefined or not an object,_.get
will show the same behavior as when no key is found in the provided object. eg_.get(null, "foo") -> undefined
,_.get(null, "foo", "bar") -> "bar"
. However this behavior is not defined in the docs so subject to change.
– Ian Walker-Sperber
Nov 2 '17 at 0:40
1
@Capaj you kiddin'? And who doesn't want/can't use lodash?
– Andre Figueiredo
Feb 19 '18 at 21:21
add a comment |
This is now supported by lodash using _.get(obj, property)
. See https://lodash.com/docs#get
Example from the docs:
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.get(object, 'a[0].b.c');
// → 3
_.get(object, ['a', '0', 'b', 'c']);
// → 3
_.get(object, 'a.b.c', 'default');
// → 'default'
5
This should be the only accepted answer, because this is the only one working for both dot and bracket syntax and It doesn't fail, when we have '' in the string of a key in the path.
– Capaj
Aug 4 '15 at 2:12
5
This. Plus, it supports_.set(...)
– Josh C.
Aug 22 '17 at 6:23
what happes if the objet is not found?
– DDave
Oct 31 '17 at 16:58
@DDave if the value passed as the object is undefined or not an object,_.get
will show the same behavior as when no key is found in the provided object. eg_.get(null, "foo") -> undefined
,_.get(null, "foo", "bar") -> "bar"
. However this behavior is not defined in the docs so subject to change.
– Ian Walker-Sperber
Nov 2 '17 at 0:40
1
@Capaj you kiddin'? And who doesn't want/can't use lodash?
– Andre Figueiredo
Feb 19 '18 at 21:21
add a comment |
This is now supported by lodash using _.get(obj, property)
. See https://lodash.com/docs#get
Example from the docs:
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.get(object, 'a[0].b.c');
// → 3
_.get(object, ['a', '0', 'b', 'c']);
// → 3
_.get(object, 'a.b.c', 'default');
// → 'default'
This is now supported by lodash using _.get(obj, property)
. See https://lodash.com/docs#get
Example from the docs:
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.get(object, 'a[0].b.c');
// → 3
_.get(object, ['a', '0', 'b', 'c']);
// → 3
_.get(object, 'a.b.c', 'default');
// → 'default'
answered Jul 8 '15 at 20:59
Ian Walker-SperberIan Walker-Sperber
1,6582915
1,6582915
5
This should be the only accepted answer, because this is the only one working for both dot and bracket syntax and It doesn't fail, when we have '' in the string of a key in the path.
– Capaj
Aug 4 '15 at 2:12
5
This. Plus, it supports_.set(...)
– Josh C.
Aug 22 '17 at 6:23
what happes if the objet is not found?
– DDave
Oct 31 '17 at 16:58
@DDave if the value passed as the object is undefined or not an object,_.get
will show the same behavior as when no key is found in the provided object. eg_.get(null, "foo") -> undefined
,_.get(null, "foo", "bar") -> "bar"
. However this behavior is not defined in the docs so subject to change.
– Ian Walker-Sperber
Nov 2 '17 at 0:40
1
@Capaj you kiddin'? And who doesn't want/can't use lodash?
– Andre Figueiredo
Feb 19 '18 at 21:21
add a comment |
5
This should be the only accepted answer, because this is the only one working for both dot and bracket syntax and It doesn't fail, when we have '' in the string of a key in the path.
– Capaj
Aug 4 '15 at 2:12
5
This. Plus, it supports_.set(...)
– Josh C.
Aug 22 '17 at 6:23
what happes if the objet is not found?
– DDave
Oct 31 '17 at 16:58
@DDave if the value passed as the object is undefined or not an object,_.get
will show the same behavior as when no key is found in the provided object. eg_.get(null, "foo") -> undefined
,_.get(null, "foo", "bar") -> "bar"
. However this behavior is not defined in the docs so subject to change.
– Ian Walker-Sperber
Nov 2 '17 at 0:40
1
@Capaj you kiddin'? And who doesn't want/can't use lodash?
– Andre Figueiredo
Feb 19 '18 at 21:21
5
5
This should be the only accepted answer, because this is the only one working for both dot and bracket syntax and It doesn't fail, when we have '' in the string of a key in the path.
– Capaj
Aug 4 '15 at 2:12
This should be the only accepted answer, because this is the only one working for both dot and bracket syntax and It doesn't fail, when we have '' in the string of a key in the path.
– Capaj
Aug 4 '15 at 2:12
5
5
This. Plus, it supports
_.set(...)
– Josh C.
Aug 22 '17 at 6:23
This. Plus, it supports
_.set(...)
– Josh C.
Aug 22 '17 at 6:23
what happes if the objet is not found?
– DDave
Oct 31 '17 at 16:58
what happes if the objet is not found?
– DDave
Oct 31 '17 at 16:58
@DDave if the value passed as the object is undefined or not an object,
_.get
will show the same behavior as when no key is found in the provided object. eg _.get(null, "foo") -> undefined
, _.get(null, "foo", "bar") -> "bar"
. However this behavior is not defined in the docs so subject to change.– Ian Walker-Sperber
Nov 2 '17 at 0:40
@DDave if the value passed as the object is undefined or not an object,
_.get
will show the same behavior as when no key is found in the provided object. eg _.get(null, "foo") -> undefined
, _.get(null, "foo", "bar") -> "bar"
. However this behavior is not defined in the docs so subject to change.– Ian Walker-Sperber
Nov 2 '17 at 0:40
1
1
@Capaj you kiddin'? And who doesn't want/can't use lodash?
– Andre Figueiredo
Feb 19 '18 at 21:21
@Capaj you kiddin'? And who doesn't want/can't use lodash?
– Andre Figueiredo
Feb 19 '18 at 21:21
add a comment |
You'd have to parse the string yourself:
function getProperty(obj, prop) {
var parts = prop.split('.');
if (Array.isArray(parts)) {
var last = parts.pop(),
l = parts.length,
i = 1,
current = parts[0];
while((obj = obj[current]) && i < l) {
current = parts[i];
i++;
}
if(obj) {
return obj[last];
}
} else {
throw 'parts is not valid array';
}
}
This required that you also define array indexes with dot notation:
var part3name1 = "part3.0.name";
It makes the parsing easier.
DEMO
@Felix Kling : Your solution does provide me with what I need. And I thank you alot for that. But Alnitak also provide different ways and seem to work either. Since I can only choose one answer, I will choose Alnitak answer. Not that his solution is better than you or something like that. Anyway, I really appreciate your solution and effort you gave.
– Komaruloh
Jun 27 '11 at 11:25
1
@Komaruloh: Oh I thought you can always up vote answers on your own question.... anyway I was more or less kidding, I don't need more reputation ;) Happy coding!
– Felix Kling
Jun 27 '11 at 11:50
1
@Felix Kling : You need at least 15 reputation to up vote. :) I believe you don't need more reputation with 69k+ . Thanks
– Komaruloh
Jun 27 '11 at 14:58
@Felix FWIW - converting fromsyntax to property syntax is pretty trivial.
– Alnitak
Jun 27 '11 at 16:19
4
If you change the while loop towhile (l > 0 && (obj = obj[current]) && i < l)
then this code works for strings without dots as well.
– Snea
Aug 17 '14 at 6:18
|
show 2 more comments
You'd have to parse the string yourself:
function getProperty(obj, prop) {
var parts = prop.split('.');
if (Array.isArray(parts)) {
var last = parts.pop(),
l = parts.length,
i = 1,
current = parts[0];
while((obj = obj[current]) && i < l) {
current = parts[i];
i++;
}
if(obj) {
return obj[last];
}
} else {
throw 'parts is not valid array';
}
}
This required that you also define array indexes with dot notation:
var part3name1 = "part3.0.name";
It makes the parsing easier.
DEMO
@Felix Kling : Your solution does provide me with what I need. And I thank you alot for that. But Alnitak also provide different ways and seem to work either. Since I can only choose one answer, I will choose Alnitak answer. Not that his solution is better than you or something like that. Anyway, I really appreciate your solution and effort you gave.
– Komaruloh
Jun 27 '11 at 11:25
1
@Komaruloh: Oh I thought you can always up vote answers on your own question.... anyway I was more or less kidding, I don't need more reputation ;) Happy coding!
– Felix Kling
Jun 27 '11 at 11:50
1
@Felix Kling : You need at least 15 reputation to up vote. :) I believe you don't need more reputation with 69k+ . Thanks
– Komaruloh
Jun 27 '11 at 14:58
@Felix FWIW - converting fromsyntax to property syntax is pretty trivial.
– Alnitak
Jun 27 '11 at 16:19
4
If you change the while loop towhile (l > 0 && (obj = obj[current]) && i < l)
then this code works for strings without dots as well.
– Snea
Aug 17 '14 at 6:18
|
show 2 more comments
You'd have to parse the string yourself:
function getProperty(obj, prop) {
var parts = prop.split('.');
if (Array.isArray(parts)) {
var last = parts.pop(),
l = parts.length,
i = 1,
current = parts[0];
while((obj = obj[current]) && i < l) {
current = parts[i];
i++;
}
if(obj) {
return obj[last];
}
} else {
throw 'parts is not valid array';
}
}
This required that you also define array indexes with dot notation:
var part3name1 = "part3.0.name";
It makes the parsing easier.
DEMO
You'd have to parse the string yourself:
function getProperty(obj, prop) {
var parts = prop.split('.');
if (Array.isArray(parts)) {
var last = parts.pop(),
l = parts.length,
i = 1,
current = parts[0];
while((obj = obj[current]) && i < l) {
current = parts[i];
i++;
}
if(obj) {
return obj[last];
}
} else {
throw 'parts is not valid array';
}
}
This required that you also define array indexes with dot notation:
var part3name1 = "part3.0.name";
It makes the parsing easier.
DEMO
edited Dec 4 '15 at 13:46
d.danailov
7,10444230
7,10444230
answered Jun 27 '11 at 10:38
Felix KlingFelix Kling
549k126853910
549k126853910
@Felix Kling : Your solution does provide me with what I need. And I thank you alot for that. But Alnitak also provide different ways and seem to work either. Since I can only choose one answer, I will choose Alnitak answer. Not that his solution is better than you or something like that. Anyway, I really appreciate your solution and effort you gave.
– Komaruloh
Jun 27 '11 at 11:25
1
@Komaruloh: Oh I thought you can always up vote answers on your own question.... anyway I was more or less kidding, I don't need more reputation ;) Happy coding!
– Felix Kling
Jun 27 '11 at 11:50
1
@Felix Kling : You need at least 15 reputation to up vote. :) I believe you don't need more reputation with 69k+ . Thanks
– Komaruloh
Jun 27 '11 at 14:58
@Felix FWIW - converting fromsyntax to property syntax is pretty trivial.
– Alnitak
Jun 27 '11 at 16:19
4
If you change the while loop towhile (l > 0 && (obj = obj[current]) && i < l)
then this code works for strings without dots as well.
– Snea
Aug 17 '14 at 6:18
|
show 2 more comments
@Felix Kling : Your solution does provide me with what I need. And I thank you alot for that. But Alnitak also provide different ways and seem to work either. Since I can only choose one answer, I will choose Alnitak answer. Not that his solution is better than you or something like that. Anyway, I really appreciate your solution and effort you gave.
– Komaruloh
Jun 27 '11 at 11:25
1
@Komaruloh: Oh I thought you can always up vote answers on your own question.... anyway I was more or less kidding, I don't need more reputation ;) Happy coding!
– Felix Kling
Jun 27 '11 at 11:50
1
@Felix Kling : You need at least 15 reputation to up vote. :) I believe you don't need more reputation with 69k+ . Thanks
– Komaruloh
Jun 27 '11 at 14:58
@Felix FWIW - converting fromsyntax to property syntax is pretty trivial.
– Alnitak
Jun 27 '11 at 16:19
4
If you change the while loop towhile (l > 0 && (obj = obj[current]) && i < l)
then this code works for strings without dots as well.
– Snea
Aug 17 '14 at 6:18
@Felix Kling : Your solution does provide me with what I need. And I thank you alot for that. But Alnitak also provide different ways and seem to work either. Since I can only choose one answer, I will choose Alnitak answer. Not that his solution is better than you or something like that. Anyway, I really appreciate your solution and effort you gave.
– Komaruloh
Jun 27 '11 at 11:25
@Felix Kling : Your solution does provide me with what I need. And I thank you alot for that. But Alnitak also provide different ways and seem to work either. Since I can only choose one answer, I will choose Alnitak answer. Not that his solution is better than you or something like that. Anyway, I really appreciate your solution and effort you gave.
– Komaruloh
Jun 27 '11 at 11:25
1
1
@Komaruloh: Oh I thought you can always up vote answers on your own question.... anyway I was more or less kidding, I don't need more reputation ;) Happy coding!
– Felix Kling
Jun 27 '11 at 11:50
@Komaruloh: Oh I thought you can always up vote answers on your own question.... anyway I was more or less kidding, I don't need more reputation ;) Happy coding!
– Felix Kling
Jun 27 '11 at 11:50
1
1
@Felix Kling : You need at least 15 reputation to up vote. :) I believe you don't need more reputation with 69k+ . Thanks
– Komaruloh
Jun 27 '11 at 14:58
@Felix Kling : You need at least 15 reputation to up vote. :) I believe you don't need more reputation with 69k+ . Thanks
– Komaruloh
Jun 27 '11 at 14:58
@Felix FWIW - converting from
syntax to property syntax is pretty trivial.– Alnitak
Jun 27 '11 at 16:19
@Felix FWIW - converting from
syntax to property syntax is pretty trivial.– Alnitak
Jun 27 '11 at 16:19
4
4
If you change the while loop to
while (l > 0 && (obj = obj[current]) && i < l)
then this code works for strings without dots as well.– Snea
Aug 17 '14 at 6:18
If you change the while loop to
while (l > 0 && (obj = obj[current]) && i < l)
then this code works for strings without dots as well.– Snea
Aug 17 '14 at 6:18
|
show 2 more comments
Works for arrays / arrays inside the object also.
Defensive against invalid values.
/**
* Retrieve nested item from object/array
* @param {Object|Array} obj
* @param {String} path dot separated
* @param {*} def default value ( if result undefined )
* @returns {*}
*/
function path(obj, path, def){
var i, len;
for(i = 0,path = path.split('.'), len = path.length; i < len; i++){
if(!obj || typeof obj !== 'object') return def;
obj = obj[path[i]];
}
if(obj === undefined) return def;
return obj;
}
//////////////////////////
// TEST //
//////////////////////////
var arr = [true, {'sp ace': true}, true]
var obj = {
'sp ace': true,
arr: arr,
nested: {'dotted.str.ing': true},
arr3: arr
}
shouldThrow(`path(obj, "arr.0")`);
shouldBeDefined(`path(obj, "arr[0]")`);
shouldBeEqualToNumber(`path(obj, "arr.length")`, 3);
shouldBeTrue(`path(obj, "sp ace")`);
shouldBeEqualToString(`path(obj, "none.existed.prop", "fallback")`, "fallback");
shouldBeTrue(`path(obj, "nested['dotted.str.ing'])`);
<script src="https://cdn.rawgit.com/coderek/e7b30bac7634a50ad8fd/raw/174b6634c8f57aa8aac0716c5b7b2a7098e03584/js-test.js"></script>
9
Thanks this is the best and most performant answer - jsfiddle.net/Jw8XB/1
– Dominic
Jul 31 '13 at 23:00
@Endless, I'd like to emphasize the path should separate the items with dots. Braces won't work. I.e. to access first item in array use "0.sp ace".
– TheZver
Mar 27 '16 at 11:32
add a comment |
Works for arrays / arrays inside the object also.
Defensive against invalid values.
/**
* Retrieve nested item from object/array
* @param {Object|Array} obj
* @param {String} path dot separated
* @param {*} def default value ( if result undefined )
* @returns {*}
*/
function path(obj, path, def){
var i, len;
for(i = 0,path = path.split('.'), len = path.length; i < len; i++){
if(!obj || typeof obj !== 'object') return def;
obj = obj[path[i]];
}
if(obj === undefined) return def;
return obj;
}
//////////////////////////
// TEST //
//////////////////////////
var arr = [true, {'sp ace': true}, true]
var obj = {
'sp ace': true,
arr: arr,
nested: {'dotted.str.ing': true},
arr3: arr
}
shouldThrow(`path(obj, "arr.0")`);
shouldBeDefined(`path(obj, "arr[0]")`);
shouldBeEqualToNumber(`path(obj, "arr.length")`, 3);
shouldBeTrue(`path(obj, "sp ace")`);
shouldBeEqualToString(`path(obj, "none.existed.prop", "fallback")`, "fallback");
shouldBeTrue(`path(obj, "nested['dotted.str.ing'])`);
<script src="https://cdn.rawgit.com/coderek/e7b30bac7634a50ad8fd/raw/174b6634c8f57aa8aac0716c5b7b2a7098e03584/js-test.js"></script>
9
Thanks this is the best and most performant answer - jsfiddle.net/Jw8XB/1
– Dominic
Jul 31 '13 at 23:00
@Endless, I'd like to emphasize the path should separate the items with dots. Braces won't work. I.e. to access first item in array use "0.sp ace".
– TheZver
Mar 27 '16 at 11:32
add a comment |
Works for arrays / arrays inside the object also.
Defensive against invalid values.
/**
* Retrieve nested item from object/array
* @param {Object|Array} obj
* @param {String} path dot separated
* @param {*} def default value ( if result undefined )
* @returns {*}
*/
function path(obj, path, def){
var i, len;
for(i = 0,path = path.split('.'), len = path.length; i < len; i++){
if(!obj || typeof obj !== 'object') return def;
obj = obj[path[i]];
}
if(obj === undefined) return def;
return obj;
}
//////////////////////////
// TEST //
//////////////////////////
var arr = [true, {'sp ace': true}, true]
var obj = {
'sp ace': true,
arr: arr,
nested: {'dotted.str.ing': true},
arr3: arr
}
shouldThrow(`path(obj, "arr.0")`);
shouldBeDefined(`path(obj, "arr[0]")`);
shouldBeEqualToNumber(`path(obj, "arr.length")`, 3);
shouldBeTrue(`path(obj, "sp ace")`);
shouldBeEqualToString(`path(obj, "none.existed.prop", "fallback")`, "fallback");
shouldBeTrue(`path(obj, "nested['dotted.str.ing'])`);
<script src="https://cdn.rawgit.com/coderek/e7b30bac7634a50ad8fd/raw/174b6634c8f57aa8aac0716c5b7b2a7098e03584/js-test.js"></script>
Works for arrays / arrays inside the object also.
Defensive against invalid values.
/**
* Retrieve nested item from object/array
* @param {Object|Array} obj
* @param {String} path dot separated
* @param {*} def default value ( if result undefined )
* @returns {*}
*/
function path(obj, path, def){
var i, len;
for(i = 0,path = path.split('.'), len = path.length; i < len; i++){
if(!obj || typeof obj !== 'object') return def;
obj = obj[path[i]];
}
if(obj === undefined) return def;
return obj;
}
//////////////////////////
// TEST //
//////////////////////////
var arr = [true, {'sp ace': true}, true]
var obj = {
'sp ace': true,
arr: arr,
nested: {'dotted.str.ing': true},
arr3: arr
}
shouldThrow(`path(obj, "arr.0")`);
shouldBeDefined(`path(obj, "arr[0]")`);
shouldBeEqualToNumber(`path(obj, "arr.length")`, 3);
shouldBeTrue(`path(obj, "sp ace")`);
shouldBeEqualToString(`path(obj, "none.existed.prop", "fallback")`, "fallback");
shouldBeTrue(`path(obj, "nested['dotted.str.ing'])`);
<script src="https://cdn.rawgit.com/coderek/e7b30bac7634a50ad8fd/raw/174b6634c8f57aa8aac0716c5b7b2a7098e03584/js-test.js"></script>
/**
* Retrieve nested item from object/array
* @param {Object|Array} obj
* @param {String} path dot separated
* @param {*} def default value ( if result undefined )
* @returns {*}
*/
function path(obj, path, def){
var i, len;
for(i = 0,path = path.split('.'), len = path.length; i < len; i++){
if(!obj || typeof obj !== 'object') return def;
obj = obj[path[i]];
}
if(obj === undefined) return def;
return obj;
}
//////////////////////////
// TEST //
//////////////////////////
var arr = [true, {'sp ace': true}, true]
var obj = {
'sp ace': true,
arr: arr,
nested: {'dotted.str.ing': true},
arr3: arr
}
shouldThrow(`path(obj, "arr.0")`);
shouldBeDefined(`path(obj, "arr[0]")`);
shouldBeEqualToNumber(`path(obj, "arr.length")`, 3);
shouldBeTrue(`path(obj, "sp ace")`);
shouldBeEqualToString(`path(obj, "none.existed.prop", "fallback")`, "fallback");
shouldBeTrue(`path(obj, "nested['dotted.str.ing'])`);
<script src="https://cdn.rawgit.com/coderek/e7b30bac7634a50ad8fd/raw/174b6634c8f57aa8aac0716c5b7b2a7098e03584/js-test.js"></script>
/**
* Retrieve nested item from object/array
* @param {Object|Array} obj
* @param {String} path dot separated
* @param {*} def default value ( if result undefined )
* @returns {*}
*/
function path(obj, path, def){
var i, len;
for(i = 0,path = path.split('.'), len = path.length; i < len; i++){
if(!obj || typeof obj !== 'object') return def;
obj = obj[path[i]];
}
if(obj === undefined) return def;
return obj;
}
//////////////////////////
// TEST //
//////////////////////////
var arr = [true, {'sp ace': true}, true]
var obj = {
'sp ace': true,
arr: arr,
nested: {'dotted.str.ing': true},
arr3: arr
}
shouldThrow(`path(obj, "arr.0")`);
shouldBeDefined(`path(obj, "arr[0]")`);
shouldBeEqualToNumber(`path(obj, "arr.length")`, 3);
shouldBeTrue(`path(obj, "sp ace")`);
shouldBeEqualToString(`path(obj, "none.existed.prop", "fallback")`, "fallback");
shouldBeTrue(`path(obj, "nested['dotted.str.ing'])`);
<script src="https://cdn.rawgit.com/coderek/e7b30bac7634a50ad8fd/raw/174b6634c8f57aa8aac0716c5b7b2a7098e03584/js-test.js"></script>
edited Mar 27 '16 at 10:47
Endless
12.2k65070
12.2k65070
answered Apr 24 '13 at 11:24
TheZverTheZver
7462915
7462915
9
Thanks this is the best and most performant answer - jsfiddle.net/Jw8XB/1
– Dominic
Jul 31 '13 at 23:00
@Endless, I'd like to emphasize the path should separate the items with dots. Braces won't work. I.e. to access first item in array use "0.sp ace".
– TheZver
Mar 27 '16 at 11:32
add a comment |
9
Thanks this is the best and most performant answer - jsfiddle.net/Jw8XB/1
– Dominic
Jul 31 '13 at 23:00
@Endless, I'd like to emphasize the path should separate the items with dots. Braces won't work. I.e. to access first item in array use "0.sp ace".
– TheZver
Mar 27 '16 at 11:32
9
9
Thanks this is the best and most performant answer - jsfiddle.net/Jw8XB/1
– Dominic
Jul 31 '13 at 23:00
Thanks this is the best and most performant answer - jsfiddle.net/Jw8XB/1
– Dominic
Jul 31 '13 at 23:00
@Endless, I'd like to emphasize the path should separate the items with dots. Braces won't work. I.e. to access first item in array use "0.sp ace".
– TheZver
Mar 27 '16 at 11:32
@Endless, I'd like to emphasize the path should separate the items with dots. Braces won't work. I.e. to access first item in array use "0.sp ace".
– TheZver
Mar 27 '16 at 11:32
add a comment |
ES6: Only one line in Vanila JS (it return null if don't find instead of giving error):
'path.string'.split('.').reduce((p,c)=>p&&p[c]||null, MyOBJ)
or exemple:
'a.b.c'.split('.').reduce((p,c)=>p&&p[c]||null, {a:{b:{c:1}}})
For a ready to use function that also recognizes false, 0 and negative number and accept default values as parameter:
const resolvePath = (object, path, defaultValue) => path
.split('.')
.reduce((o, p) => o ? o[p] : defaultValue, object)
Exemple to use:
resolvePath(window,'document.body') => <body>
resolvePath(window,'document.body.xyz') => undefined
resolvePath(window,'document.body.xyz', null) => null
resolvePath(window,'document.body.xyz', 1) => 1
Bonus:
To set a path (Requested by @rob-gordon) you can use:
const setPath = (object, path, value) => path
.split('.')
.reduce((o,p) => o[p] = path.split('.').pop() === p ? value : o[p] || {}, object)
Example:
let myVar = {}
setPath(myVar, 'a.b.c', 42) => 42
console.log(myVar) => {a: {b: {c: 42}}}
Access array with :
const resolvePath = (object, path, defaultValue) => path
.split(/[.[]'"]/)
.filter(p => p)
.reduce((o, p) => o ? o[p] : defaultValue, object)
exemple
const myVar = {a:{b:[{c:1}]}}
resolvePath(myVar,'a.b[0].c') => 1
resolvePath(myVar,'a["b"]['0'].c') => 1
1
I love this technique. This is really messy but I wanted to use this technique for assignment.let o = {a:{b:{c:1}}}; let str = 'a.b.c'; str.split('.').splice(0, str.split('.').length - 1).reduce((p,c)=>p&&p[c]||null, o)[str.split('.').slice(-1)] = "some new value";
– rob-gordon
Jun 28 '17 at 17:15
1
I like the idea of using reduce but your logic seems off for0
,undefined
andnull
values.{a:{b:{c:0}}}
returnsnull
instead of0
. Perhaps explicitly checking for null or undefined will clear up these issues.(p,c)=>p === undefined || p === null ? undefined : p[c]
– SmujMaiku
Oct 15 '17 at 17:31
Hi @SmujMaiku, the "ready to use" function return correctly for '0', 'undefined' and 'null', I just tested on the console: resolvePath({a:{b:{c:0}}},'a.b.c',null) => 0; It check if the key exists instead of the value itself which avoid more than one check
– Adriano Spadoni
Oct 16 '17 at 9:18
here defaultValue did not work, usingReflect.has(o, k) ? ...
(ES6 Reflect.has) worked though
– Andre Figueiredo
Feb 23 '18 at 12:31
add a comment |
ES6: Only one line in Vanila JS (it return null if don't find instead of giving error):
'path.string'.split('.').reduce((p,c)=>p&&p[c]||null, MyOBJ)
or exemple:
'a.b.c'.split('.').reduce((p,c)=>p&&p[c]||null, {a:{b:{c:1}}})
For a ready to use function that also recognizes false, 0 and negative number and accept default values as parameter:
const resolvePath = (object, path, defaultValue) => path
.split('.')
.reduce((o, p) => o ? o[p] : defaultValue, object)
Exemple to use:
resolvePath(window,'document.body') => <body>
resolvePath(window,'document.body.xyz') => undefined
resolvePath(window,'document.body.xyz', null) => null
resolvePath(window,'document.body.xyz', 1) => 1
Bonus:
To set a path (Requested by @rob-gordon) you can use:
const setPath = (object, path, value) => path
.split('.')
.reduce((o,p) => o[p] = path.split('.').pop() === p ? value : o[p] || {}, object)
Example:
let myVar = {}
setPath(myVar, 'a.b.c', 42) => 42
console.log(myVar) => {a: {b: {c: 42}}}
Access array with :
const resolvePath = (object, path, defaultValue) => path
.split(/[.[]'"]/)
.filter(p => p)
.reduce((o, p) => o ? o[p] : defaultValue, object)
exemple
const myVar = {a:{b:[{c:1}]}}
resolvePath(myVar,'a.b[0].c') => 1
resolvePath(myVar,'a["b"]['0'].c') => 1
1
I love this technique. This is really messy but I wanted to use this technique for assignment.let o = {a:{b:{c:1}}}; let str = 'a.b.c'; str.split('.').splice(0, str.split('.').length - 1).reduce((p,c)=>p&&p[c]||null, o)[str.split('.').slice(-1)] = "some new value";
– rob-gordon
Jun 28 '17 at 17:15
1
I like the idea of using reduce but your logic seems off for0
,undefined
andnull
values.{a:{b:{c:0}}}
returnsnull
instead of0
. Perhaps explicitly checking for null or undefined will clear up these issues.(p,c)=>p === undefined || p === null ? undefined : p[c]
– SmujMaiku
Oct 15 '17 at 17:31
Hi @SmujMaiku, the "ready to use" function return correctly for '0', 'undefined' and 'null', I just tested on the console: resolvePath({a:{b:{c:0}}},'a.b.c',null) => 0; It check if the key exists instead of the value itself which avoid more than one check
– Adriano Spadoni
Oct 16 '17 at 9:18
here defaultValue did not work, usingReflect.has(o, k) ? ...
(ES6 Reflect.has) worked though
– Andre Figueiredo
Feb 23 '18 at 12:31
add a comment |
ES6: Only one line in Vanila JS (it return null if don't find instead of giving error):
'path.string'.split('.').reduce((p,c)=>p&&p[c]||null, MyOBJ)
or exemple:
'a.b.c'.split('.').reduce((p,c)=>p&&p[c]||null, {a:{b:{c:1}}})
For a ready to use function that also recognizes false, 0 and negative number and accept default values as parameter:
const resolvePath = (object, path, defaultValue) => path
.split('.')
.reduce((o, p) => o ? o[p] : defaultValue, object)
Exemple to use:
resolvePath(window,'document.body') => <body>
resolvePath(window,'document.body.xyz') => undefined
resolvePath(window,'document.body.xyz', null) => null
resolvePath(window,'document.body.xyz', 1) => 1
Bonus:
To set a path (Requested by @rob-gordon) you can use:
const setPath = (object, path, value) => path
.split('.')
.reduce((o,p) => o[p] = path.split('.').pop() === p ? value : o[p] || {}, object)
Example:
let myVar = {}
setPath(myVar, 'a.b.c', 42) => 42
console.log(myVar) => {a: {b: {c: 42}}}
Access array with :
const resolvePath = (object, path, defaultValue) => path
.split(/[.[]'"]/)
.filter(p => p)
.reduce((o, p) => o ? o[p] : defaultValue, object)
exemple
const myVar = {a:{b:[{c:1}]}}
resolvePath(myVar,'a.b[0].c') => 1
resolvePath(myVar,'a["b"]['0'].c') => 1
ES6: Only one line in Vanila JS (it return null if don't find instead of giving error):
'path.string'.split('.').reduce((p,c)=>p&&p[c]||null, MyOBJ)
or exemple:
'a.b.c'.split('.').reduce((p,c)=>p&&p[c]||null, {a:{b:{c:1}}})
For a ready to use function that also recognizes false, 0 and negative number and accept default values as parameter:
const resolvePath = (object, path, defaultValue) => path
.split('.')
.reduce((o, p) => o ? o[p] : defaultValue, object)
Exemple to use:
resolvePath(window,'document.body') => <body>
resolvePath(window,'document.body.xyz') => undefined
resolvePath(window,'document.body.xyz', null) => null
resolvePath(window,'document.body.xyz', 1) => 1
Bonus:
To set a path (Requested by @rob-gordon) you can use:
const setPath = (object, path, value) => path
.split('.')
.reduce((o,p) => o[p] = path.split('.').pop() === p ? value : o[p] || {}, object)
Example:
let myVar = {}
setPath(myVar, 'a.b.c', 42) => 42
console.log(myVar) => {a: {b: {c: 42}}}
Access array with :
const resolvePath = (object, path, defaultValue) => path
.split(/[.[]'"]/)
.filter(p => p)
.reduce((o, p) => o ? o[p] : defaultValue, object)
exemple
const myVar = {a:{b:[{c:1}]}}
resolvePath(myVar,'a.b[0].c') => 1
resolvePath(myVar,'a["b"]['0'].c') => 1
edited Sep 19 '17 at 19:05
answered May 8 '17 at 13:38
Adriano SpadoniAdriano Spadoni
2,1051925
2,1051925
1
I love this technique. This is really messy but I wanted to use this technique for assignment.let o = {a:{b:{c:1}}}; let str = 'a.b.c'; str.split('.').splice(0, str.split('.').length - 1).reduce((p,c)=>p&&p[c]||null, o)[str.split('.').slice(-1)] = "some new value";
– rob-gordon
Jun 28 '17 at 17:15
1
I like the idea of using reduce but your logic seems off for0
,undefined
andnull
values.{a:{b:{c:0}}}
returnsnull
instead of0
. Perhaps explicitly checking for null or undefined will clear up these issues.(p,c)=>p === undefined || p === null ? undefined : p[c]
– SmujMaiku
Oct 15 '17 at 17:31
Hi @SmujMaiku, the "ready to use" function return correctly for '0', 'undefined' and 'null', I just tested on the console: resolvePath({a:{b:{c:0}}},'a.b.c',null) => 0; It check if the key exists instead of the value itself which avoid more than one check
– Adriano Spadoni
Oct 16 '17 at 9:18
here defaultValue did not work, usingReflect.has(o, k) ? ...
(ES6 Reflect.has) worked though
– Andre Figueiredo
Feb 23 '18 at 12:31
add a comment |
1
I love this technique. This is really messy but I wanted to use this technique for assignment.let o = {a:{b:{c:1}}}; let str = 'a.b.c'; str.split('.').splice(0, str.split('.').length - 1).reduce((p,c)=>p&&p[c]||null, o)[str.split('.').slice(-1)] = "some new value";
– rob-gordon
Jun 28 '17 at 17:15
1
I like the idea of using reduce but your logic seems off for0
,undefined
andnull
values.{a:{b:{c:0}}}
returnsnull
instead of0
. Perhaps explicitly checking for null or undefined will clear up these issues.(p,c)=>p === undefined || p === null ? undefined : p[c]
– SmujMaiku
Oct 15 '17 at 17:31
Hi @SmujMaiku, the "ready to use" function return correctly for '0', 'undefined' and 'null', I just tested on the console: resolvePath({a:{b:{c:0}}},'a.b.c',null) => 0; It check if the key exists instead of the value itself which avoid more than one check
– Adriano Spadoni
Oct 16 '17 at 9:18
here defaultValue did not work, usingReflect.has(o, k) ? ...
(ES6 Reflect.has) worked though
– Andre Figueiredo
Feb 23 '18 at 12:31
1
1
I love this technique. This is really messy but I wanted to use this technique for assignment.
let o = {a:{b:{c:1}}}; let str = 'a.b.c'; str.split('.').splice(0, str.split('.').length - 1).reduce((p,c)=>p&&p[c]||null, o)[str.split('.').slice(-1)] = "some new value";
– rob-gordon
Jun 28 '17 at 17:15
I love this technique. This is really messy but I wanted to use this technique for assignment.
let o = {a:{b:{c:1}}}; let str = 'a.b.c'; str.split('.').splice(0, str.split('.').length - 1).reduce((p,c)=>p&&p[c]||null, o)[str.split('.').slice(-1)] = "some new value";
– rob-gordon
Jun 28 '17 at 17:15
1
1
I like the idea of using reduce but your logic seems off for
0
, undefined
and null
values. {a:{b:{c:0}}}
returns null
instead of 0
. Perhaps explicitly checking for null or undefined will clear up these issues. (p,c)=>p === undefined || p === null ? undefined : p[c]
– SmujMaiku
Oct 15 '17 at 17:31
I like the idea of using reduce but your logic seems off for
0
, undefined
and null
values. {a:{b:{c:0}}}
returns null
instead of 0
. Perhaps explicitly checking for null or undefined will clear up these issues. (p,c)=>p === undefined || p === null ? undefined : p[c]
– SmujMaiku
Oct 15 '17 at 17:31
Hi @SmujMaiku, the "ready to use" function return correctly for '0', 'undefined' and 'null', I just tested on the console: resolvePath({a:{b:{c:0}}},'a.b.c',null) => 0; It check if the key exists instead of the value itself which avoid more than one check
– Adriano Spadoni
Oct 16 '17 at 9:18
Hi @SmujMaiku, the "ready to use" function return correctly for '0', 'undefined' and 'null', I just tested on the console: resolvePath({a:{b:{c:0}}},'a.b.c',null) => 0; It check if the key exists instead of the value itself which avoid more than one check
– Adriano Spadoni
Oct 16 '17 at 9:18
here defaultValue did not work, using
Reflect.has(o, k) ? ...
(ES6 Reflect.has) worked though– Andre Figueiredo
Feb 23 '18 at 12:31
here defaultValue did not work, using
Reflect.has(o, k) ? ...
(ES6 Reflect.has) worked though– Andre Figueiredo
Feb 23 '18 at 12:31
add a comment |
using eval:
var part1name = eval("someObject.part1.name");
wrap to return undefined on error
function path(obj, path) {
try {
return eval("obj." + path);
} catch(e) {
return undefined;
}
}
http://jsfiddle.net/shanimal/b3xTw/
Please use common sense and caution when wielding the power of eval. It's a bit like a light saber, if you turn it on there's a 90% chance you'll sever a limb. Its not for everybody.
5
Whether or not eval is a good idea depends on where the property string data is coming from. I doubt you have any reason to be concerned for hackers breaking in via a static "var p='a.b.c';eval(p);" type call. It's a perfectly fine idea for that.
– James Wilkins
Aug 21 '14 at 22:39
add a comment |
using eval:
var part1name = eval("someObject.part1.name");
wrap to return undefined on error
function path(obj, path) {
try {
return eval("obj." + path);
} catch(e) {
return undefined;
}
}
http://jsfiddle.net/shanimal/b3xTw/
Please use common sense and caution when wielding the power of eval. It's a bit like a light saber, if you turn it on there's a 90% chance you'll sever a limb. Its not for everybody.
5
Whether or not eval is a good idea depends on where the property string data is coming from. I doubt you have any reason to be concerned for hackers breaking in via a static "var p='a.b.c';eval(p);" type call. It's a perfectly fine idea for that.
– James Wilkins
Aug 21 '14 at 22:39
add a comment |
using eval:
var part1name = eval("someObject.part1.name");
wrap to return undefined on error
function path(obj, path) {
try {
return eval("obj." + path);
} catch(e) {
return undefined;
}
}
http://jsfiddle.net/shanimal/b3xTw/
Please use common sense and caution when wielding the power of eval. It's a bit like a light saber, if you turn it on there's a 90% chance you'll sever a limb. Its not for everybody.
using eval:
var part1name = eval("someObject.part1.name");
wrap to return undefined on error
function path(obj, path) {
try {
return eval("obj." + path);
} catch(e) {
return undefined;
}
}
http://jsfiddle.net/shanimal/b3xTw/
Please use common sense and caution when wielding the power of eval. It's a bit like a light saber, if you turn it on there's a 90% chance you'll sever a limb. Its not for everybody.
edited Apr 24 '14 at 6:55
community wiki
5 revs, 2 users 91%
Shanimal
5
Whether or not eval is a good idea depends on where the property string data is coming from. I doubt you have any reason to be concerned for hackers breaking in via a static "var p='a.b.c';eval(p);" type call. It's a perfectly fine idea for that.
– James Wilkins
Aug 21 '14 at 22:39
add a comment |
5
Whether or not eval is a good idea depends on where the property string data is coming from. I doubt you have any reason to be concerned for hackers breaking in via a static "var p='a.b.c';eval(p);" type call. It's a perfectly fine idea for that.
– James Wilkins
Aug 21 '14 at 22:39
5
5
Whether or not eval is a good idea depends on where the property string data is coming from. I doubt you have any reason to be concerned for hackers breaking in via a static "var p='a.b.c';eval(p);" type call. It's a perfectly fine idea for that.
– James Wilkins
Aug 21 '14 at 22:39
Whether or not eval is a good idea depends on where the property string data is coming from. I doubt you have any reason to be concerned for hackers breaking in via a static "var p='a.b.c';eval(p);" type call. It's a perfectly fine idea for that.
– James Wilkins
Aug 21 '14 at 22:39
add a comment |
You can manage to obtain value of a deep object member with dot notation without any external JavaScript library with the simple following trick:
new Function('_', 'return _.' + path)(obj);
In your case to obtain value of part1.name
from someObject
just do:
new Function('_', 'return _.part1.name')(someObject);
Here is a simple fiddle demo: https://jsfiddle.net/harishanchu/oq5esowf/
2
function deep_value ( obj, path ) { return new Function( 'o', 'return o.' + path )( obj ); }
– ArcangelZith
Jul 29 '16 at 4:59
add a comment |
You can manage to obtain value of a deep object member with dot notation without any external JavaScript library with the simple following trick:
new Function('_', 'return _.' + path)(obj);
In your case to obtain value of part1.name
from someObject
just do:
new Function('_', 'return _.part1.name')(someObject);
Here is a simple fiddle demo: https://jsfiddle.net/harishanchu/oq5esowf/
2
function deep_value ( obj, path ) { return new Function( 'o', 'return o.' + path )( obj ); }
– ArcangelZith
Jul 29 '16 at 4:59
add a comment |
You can manage to obtain value of a deep object member with dot notation without any external JavaScript library with the simple following trick:
new Function('_', 'return _.' + path)(obj);
In your case to obtain value of part1.name
from someObject
just do:
new Function('_', 'return _.part1.name')(someObject);
Here is a simple fiddle demo: https://jsfiddle.net/harishanchu/oq5esowf/
You can manage to obtain value of a deep object member with dot notation without any external JavaScript library with the simple following trick:
new Function('_', 'return _.' + path)(obj);
In your case to obtain value of part1.name
from someObject
just do:
new Function('_', 'return _.part1.name')(someObject);
Here is a simple fiddle demo: https://jsfiddle.net/harishanchu/oq5esowf/
edited Feb 24 '16 at 11:43
answered Apr 11 '15 at 10:22
Harish AnchuHarish Anchu
5,82941951
5,82941951
2
function deep_value ( obj, path ) { return new Function( 'o', 'return o.' + path )( obj ); }
– ArcangelZith
Jul 29 '16 at 4:59
add a comment |
2
function deep_value ( obj, path ) { return new Function( 'o', 'return o.' + path )( obj ); }
– ArcangelZith
Jul 29 '16 at 4:59
2
2
function deep_value ( obj, path ) { return new Function( 'o', 'return o.' + path )( obj ); }
– ArcangelZith
Jul 29 '16 at 4:59
function deep_value ( obj, path ) { return new Function( 'o', 'return o.' + path )( obj ); }
– ArcangelZith
Jul 29 '16 at 4:59
add a comment |
Here I offer more ways, which seem faster in many respects:
Option 1: Split string on . or [ or ] or ' or ", reverse it, skip empty items.
function getValue(path, origin) {
if (origin === void 0 || origin === null) origin = self ? self : this;
if (typeof path !== 'string') path = '' + path;
var parts = path.split(/[|]|.|'|"/g).reverse(), name; // (why reverse? because it's usually faster to pop off the end of an array)
while (parts.length) { name=parts.pop(); if (name) origin=origin[name]; }
return origin;
}
Option 2 (fastest of all, except eval
): Low level character scan (no regex/split/etc, just a quick char scan).
Note: This one does not support quotes for indexes.
function getValue(path, origin) {
if (origin === void 0 || origin === null) origin = self ? self : this;
if (typeof path !== 'string') path = '' + path;
var c = '', pc, i = 0, n = path.length, name = '';
if (n) while (i<=n) ((c = path[i++]) == '.' || c == '[' || c == ']' || c == void 0) ? (name?(origin = origin[name], name = ''):(pc=='.'||pc=='['||pc==']'&&c==']'?i=n+2:void 0),pc=c) : name += c;
if (i==n+2) throw "Invalid path: "+path;
return origin;
} // (around 1,000,000+/- ops/sec)
Option 3: (new: option 2 expanded to support quotes - a bit slower, but still fast)
function getValue(path, origin) {
if (origin === void 0 || origin === null) origin = self ? self : this;
if (typeof path !== 'string') path = '' + path;
var c, pc, i = 0, n = path.length, name = '', q;
while (i<=n)
((c = path[i++]) == '.' || c == '[' || c == ']' || c == "'" || c == '"' || c == void 0) ? (c==q&&path[i]==']'?q='':q?name+=c:name?(origin?origin=origin[name]:i=n+2,name='') : (pc=='['&&(c=='"'||c=="'")?q=c:pc=='.'||pc=='['||pc==']'&&c==']'||pc=='"'||pc=="'"?i=n+2:void 0), pc=c) : name += c;
if (i==n+2 || name) throw "Invalid path: "+path;
return origin;
}
JSPerf: http://jsperf.com/ways-to-dereference-a-delimited-property-string/3
"eval(...)" is still king though (performance wise that is). If you have property paths directly under your control, there shouldn't be any issues with using 'eval' (especially if speed is desired). If pulling property paths "over the wire" (on the line!? lol :P), then yes, use something else to be safe. Only an idiot would say to never use "eval" at all, as there ARE good reasons when to use it. Also, "It is used in Doug Crockford's JSON parser." If the input is safe, then no problems at all. Use the right tool for the right job, that's it.
add a comment |
Here I offer more ways, which seem faster in many respects:
Option 1: Split string on . or [ or ] or ' or ", reverse it, skip empty items.
function getValue(path, origin) {
if (origin === void 0 || origin === null) origin = self ? self : this;
if (typeof path !== 'string') path = '' + path;
var parts = path.split(/[|]|.|'|"/g).reverse(), name; // (why reverse? because it's usually faster to pop off the end of an array)
while (parts.length) { name=parts.pop(); if (name) origin=origin[name]; }
return origin;
}
Option 2 (fastest of all, except eval
): Low level character scan (no regex/split/etc, just a quick char scan).
Note: This one does not support quotes for indexes.
function getValue(path, origin) {
if (origin === void 0 || origin === null) origin = self ? self : this;
if (typeof path !== 'string') path = '' + path;
var c = '', pc, i = 0, n = path.length, name = '';
if (n) while (i<=n) ((c = path[i++]) == '.' || c == '[' || c == ']' || c == void 0) ? (name?(origin = origin[name], name = ''):(pc=='.'||pc=='['||pc==']'&&c==']'?i=n+2:void 0),pc=c) : name += c;
if (i==n+2) throw "Invalid path: "+path;
return origin;
} // (around 1,000,000+/- ops/sec)
Option 3: (new: option 2 expanded to support quotes - a bit slower, but still fast)
function getValue(path, origin) {
if (origin === void 0 || origin === null) origin = self ? self : this;
if (typeof path !== 'string') path = '' + path;
var c, pc, i = 0, n = path.length, name = '', q;
while (i<=n)
((c = path[i++]) == '.' || c == '[' || c == ']' || c == "'" || c == '"' || c == void 0) ? (c==q&&path[i]==']'?q='':q?name+=c:name?(origin?origin=origin[name]:i=n+2,name='') : (pc=='['&&(c=='"'||c=="'")?q=c:pc=='.'||pc=='['||pc==']'&&c==']'||pc=='"'||pc=="'"?i=n+2:void 0), pc=c) : name += c;
if (i==n+2 || name) throw "Invalid path: "+path;
return origin;
}
JSPerf: http://jsperf.com/ways-to-dereference-a-delimited-property-string/3
"eval(...)" is still king though (performance wise that is). If you have property paths directly under your control, there shouldn't be any issues with using 'eval' (especially if speed is desired). If pulling property paths "over the wire" (on the line!? lol :P), then yes, use something else to be safe. Only an idiot would say to never use "eval" at all, as there ARE good reasons when to use it. Also, "It is used in Doug Crockford's JSON parser." If the input is safe, then no problems at all. Use the right tool for the right job, that's it.
add a comment |
Here I offer more ways, which seem faster in many respects:
Option 1: Split string on . or [ or ] or ' or ", reverse it, skip empty items.
function getValue(path, origin) {
if (origin === void 0 || origin === null) origin = self ? self : this;
if (typeof path !== 'string') path = '' + path;
var parts = path.split(/[|]|.|'|"/g).reverse(), name; // (why reverse? because it's usually faster to pop off the end of an array)
while (parts.length) { name=parts.pop(); if (name) origin=origin[name]; }
return origin;
}
Option 2 (fastest of all, except eval
): Low level character scan (no regex/split/etc, just a quick char scan).
Note: This one does not support quotes for indexes.
function getValue(path, origin) {
if (origin === void 0 || origin === null) origin = self ? self : this;
if (typeof path !== 'string') path = '' + path;
var c = '', pc, i = 0, n = path.length, name = '';
if (n) while (i<=n) ((c = path[i++]) == '.' || c == '[' || c == ']' || c == void 0) ? (name?(origin = origin[name], name = ''):(pc=='.'||pc=='['||pc==']'&&c==']'?i=n+2:void 0),pc=c) : name += c;
if (i==n+2) throw "Invalid path: "+path;
return origin;
} // (around 1,000,000+/- ops/sec)
Option 3: (new: option 2 expanded to support quotes - a bit slower, but still fast)
function getValue(path, origin) {
if (origin === void 0 || origin === null) origin = self ? self : this;
if (typeof path !== 'string') path = '' + path;
var c, pc, i = 0, n = path.length, name = '', q;
while (i<=n)
((c = path[i++]) == '.' || c == '[' || c == ']' || c == "'" || c == '"' || c == void 0) ? (c==q&&path[i]==']'?q='':q?name+=c:name?(origin?origin=origin[name]:i=n+2,name='') : (pc=='['&&(c=='"'||c=="'")?q=c:pc=='.'||pc=='['||pc==']'&&c==']'||pc=='"'||pc=="'"?i=n+2:void 0), pc=c) : name += c;
if (i==n+2 || name) throw "Invalid path: "+path;
return origin;
}
JSPerf: http://jsperf.com/ways-to-dereference-a-delimited-property-string/3
"eval(...)" is still king though (performance wise that is). If you have property paths directly under your control, there shouldn't be any issues with using 'eval' (especially if speed is desired). If pulling property paths "over the wire" (on the line!? lol :P), then yes, use something else to be safe. Only an idiot would say to never use "eval" at all, as there ARE good reasons when to use it. Also, "It is used in Doug Crockford's JSON parser." If the input is safe, then no problems at all. Use the right tool for the right job, that's it.
Here I offer more ways, which seem faster in many respects:
Option 1: Split string on . or [ or ] or ' or ", reverse it, skip empty items.
function getValue(path, origin) {
if (origin === void 0 || origin === null) origin = self ? self : this;
if (typeof path !== 'string') path = '' + path;
var parts = path.split(/[|]|.|'|"/g).reverse(), name; // (why reverse? because it's usually faster to pop off the end of an array)
while (parts.length) { name=parts.pop(); if (name) origin=origin[name]; }
return origin;
}
Option 2 (fastest of all, except eval
): Low level character scan (no regex/split/etc, just a quick char scan).
Note: This one does not support quotes for indexes.
function getValue(path, origin) {
if (origin === void 0 || origin === null) origin = self ? self : this;
if (typeof path !== 'string') path = '' + path;
var c = '', pc, i = 0, n = path.length, name = '';
if (n) while (i<=n) ((c = path[i++]) == '.' || c == '[' || c == ']' || c == void 0) ? (name?(origin = origin[name], name = ''):(pc=='.'||pc=='['||pc==']'&&c==']'?i=n+2:void 0),pc=c) : name += c;
if (i==n+2) throw "Invalid path: "+path;
return origin;
} // (around 1,000,000+/- ops/sec)
Option 3: (new: option 2 expanded to support quotes - a bit slower, but still fast)
function getValue(path, origin) {
if (origin === void 0 || origin === null) origin = self ? self : this;
if (typeof path !== 'string') path = '' + path;
var c, pc, i = 0, n = path.length, name = '', q;
while (i<=n)
((c = path[i++]) == '.' || c == '[' || c == ']' || c == "'" || c == '"' || c == void 0) ? (c==q&&path[i]==']'?q='':q?name+=c:name?(origin?origin=origin[name]:i=n+2,name='') : (pc=='['&&(c=='"'||c=="'")?q=c:pc=='.'||pc=='['||pc==']'&&c==']'||pc=='"'||pc=="'"?i=n+2:void 0), pc=c) : name += c;
if (i==n+2 || name) throw "Invalid path: "+path;
return origin;
}
JSPerf: http://jsperf.com/ways-to-dereference-a-delimited-property-string/3
"eval(...)" is still king though (performance wise that is). If you have property paths directly under your control, there shouldn't be any issues with using 'eval' (especially if speed is desired). If pulling property paths "over the wire" (on the line!? lol :P), then yes, use something else to be safe. Only an idiot would say to never use "eval" at all, as there ARE good reasons when to use it. Also, "It is used in Doug Crockford's JSON parser." If the input is safe, then no problems at all. Use the right tool for the right job, that's it.
edited May 23 '17 at 11:55
Community♦
11
11
answered Aug 21 '14 at 22:12
James WilkinsJames Wilkins
3,1392235
3,1392235
add a comment |
add a comment |
This will probably never see the light of day... but here it is anyway.
- Replace
bracket syntax with
.
- Split on
.
character - Remove blank strings
- Find the path (otherwise
undefined
)
// "one liner" (ES6)
const deep_value = (obj, path) =>
path
.replace(/[|].?/g, '.')
.split('.')
.filter(s => s)
.reduce((acc, val) => acc && acc[val], obj);
// ... and that's it.
var someObject = {
'part1' : {
'name': 'Part 1',
'size': '20',
'qty' : '50'
},
'part2' : {
'name': 'Part 2',
'size': '15',
'qty' : '60'
},
'part3' : [
{
'name': 'Part 3A',
'size': '10',
'qty' : '20'
}
// ...
]
};
console.log(deep_value(someObject, "part1.name")); // Part 1
console.log(deep_value(someObject, "part2.qty")); // 60
console.log(deep_value(someObject, "part3[0].name")); // Part 3A
1
It did see the light of the day!! thanks
– abann sunny
Jan 15 at 21:01
add a comment |
This will probably never see the light of day... but here it is anyway.
- Replace
bracket syntax with
.
- Split on
.
character - Remove blank strings
- Find the path (otherwise
undefined
)
// "one liner" (ES6)
const deep_value = (obj, path) =>
path
.replace(/[|].?/g, '.')
.split('.')
.filter(s => s)
.reduce((acc, val) => acc && acc[val], obj);
// ... and that's it.
var someObject = {
'part1' : {
'name': 'Part 1',
'size': '20',
'qty' : '50'
},
'part2' : {
'name': 'Part 2',
'size': '15',
'qty' : '60'
},
'part3' : [
{
'name': 'Part 3A',
'size': '10',
'qty' : '20'
}
// ...
]
};
console.log(deep_value(someObject, "part1.name")); // Part 1
console.log(deep_value(someObject, "part2.qty")); // 60
console.log(deep_value(someObject, "part3[0].name")); // Part 3A
1
It did see the light of the day!! thanks
– abann sunny
Jan 15 at 21:01
add a comment |
This will probably never see the light of day... but here it is anyway.
- Replace
bracket syntax with
.
- Split on
.
character - Remove blank strings
- Find the path (otherwise
undefined
)
// "one liner" (ES6)
const deep_value = (obj, path) =>
path
.replace(/[|].?/g, '.')
.split('.')
.filter(s => s)
.reduce((acc, val) => acc && acc[val], obj);
// ... and that's it.
var someObject = {
'part1' : {
'name': 'Part 1',
'size': '20',
'qty' : '50'
},
'part2' : {
'name': 'Part 2',
'size': '15',
'qty' : '60'
},
'part3' : [
{
'name': 'Part 3A',
'size': '10',
'qty' : '20'
}
// ...
]
};
console.log(deep_value(someObject, "part1.name")); // Part 1
console.log(deep_value(someObject, "part2.qty")); // 60
console.log(deep_value(someObject, "part3[0].name")); // Part 3A
This will probably never see the light of day... but here it is anyway.
- Replace
bracket syntax with
.
- Split on
.
character - Remove blank strings
- Find the path (otherwise
undefined
)
// "one liner" (ES6)
const deep_value = (obj, path) =>
path
.replace(/[|].?/g, '.')
.split('.')
.filter(s => s)
.reduce((acc, val) => acc && acc[val], obj);
// ... and that's it.
var someObject = {
'part1' : {
'name': 'Part 1',
'size': '20',
'qty' : '50'
},
'part2' : {
'name': 'Part 2',
'size': '15',
'qty' : '60'
},
'part3' : [
{
'name': 'Part 3A',
'size': '10',
'qty' : '20'
}
// ...
]
};
console.log(deep_value(someObject, "part1.name")); // Part 1
console.log(deep_value(someObject, "part2.qty")); // 60
console.log(deep_value(someObject, "part3[0].name")); // Part 3A
// "one liner" (ES6)
const deep_value = (obj, path) =>
path
.replace(/[|].?/g, '.')
.split('.')
.filter(s => s)
.reduce((acc, val) => acc && acc[val], obj);
// ... and that's it.
var someObject = {
'part1' : {
'name': 'Part 1',
'size': '20',
'qty' : '50'
},
'part2' : {
'name': 'Part 2',
'size': '15',
'qty' : '60'
},
'part3' : [
{
'name': 'Part 3A',
'size': '10',
'qty' : '20'
}
// ...
]
};
console.log(deep_value(someObject, "part1.name")); // Part 1
console.log(deep_value(someObject, "part2.qty")); // 60
console.log(deep_value(someObject, "part3[0].name")); // Part 3A
// "one liner" (ES6)
const deep_value = (obj, path) =>
path
.replace(/[|].?/g, '.')
.split('.')
.filter(s => s)
.reduce((acc, val) => acc && acc[val], obj);
// ... and that's it.
var someObject = {
'part1' : {
'name': 'Part 1',
'size': '20',
'qty' : '50'
},
'part2' : {
'name': 'Part 2',
'size': '15',
'qty' : '60'
},
'part3' : [
{
'name': 'Part 3A',
'size': '10',
'qty' : '20'
}
// ...
]
};
console.log(deep_value(someObject, "part1.name")); // Part 1
console.log(deep_value(someObject, "part2.qty")); // 60
console.log(deep_value(someObject, "part3[0].name")); // Part 3A
edited Nov 10 '18 at 13:24
answered Jun 26 '18 at 18:16
Nick GrealyNick Grealy
10.7k65778
10.7k65778
1
It did see the light of the day!! thanks
– abann sunny
Jan 15 at 21:01
add a comment |
1
It did see the light of the day!! thanks
– abann sunny
Jan 15 at 21:01
1
1
It did see the light of the day!! thanks
– abann sunny
Jan 15 at 21:01
It did see the light of the day!! thanks
– abann sunny
Jan 15 at 21:01
add a comment |
I think you are asking for this:
var part1name = someObject.part1.name;
var part2quantity = someObject.part2.qty;
var part3name1 = someObject.part3[0].name;
You could be asking for this:
var part1name = someObject["part1"]["name"];
var part2quantity = someObject["part2"]["qty"];
var part3name1 = someObject["part3"][0]["name"];
Both of which will work
Or maybe you are asking for this
var partName = "part1";
var nameStr = "name";
var part1name = someObject[partName][nameStr];
Finally you could be asking for this
var partName = "part1.name";
var partBits = partName.split(".");
var part1name = someObject[partBits[0]][partBits[1]];
I think OP's asking for the last solution. However, strings don't haveSplit
method, but rathersplit
.
– duri
Jun 27 '11 at 10:37
Actualy I was asking the last one. The partName variable is filled with string indicating the key-structure to value. Your solution seems makes sense. However I may need to modify for extended depth in the data, like 4-5 level and more. And I am wondering if I can treat the array and object uniformly with this?
– Komaruloh
Jun 27 '11 at 10:38
add a comment |
I think you are asking for this:
var part1name = someObject.part1.name;
var part2quantity = someObject.part2.qty;
var part3name1 = someObject.part3[0].name;
You could be asking for this:
var part1name = someObject["part1"]["name"];
var part2quantity = someObject["part2"]["qty"];
var part3name1 = someObject["part3"][0]["name"];
Both of which will work
Or maybe you are asking for this
var partName = "part1";
var nameStr = "name";
var part1name = someObject[partName][nameStr];
Finally you could be asking for this
var partName = "part1.name";
var partBits = partName.split(".");
var part1name = someObject[partBits[0]][partBits[1]];
I think OP's asking for the last solution. However, strings don't haveSplit
method, but rathersplit
.
– duri
Jun 27 '11 at 10:37
Actualy I was asking the last one. The partName variable is filled with string indicating the key-structure to value. Your solution seems makes sense. However I may need to modify for extended depth in the data, like 4-5 level and more. And I am wondering if I can treat the array and object uniformly with this?
– Komaruloh
Jun 27 '11 at 10:38
add a comment |
I think you are asking for this:
var part1name = someObject.part1.name;
var part2quantity = someObject.part2.qty;
var part3name1 = someObject.part3[0].name;
You could be asking for this:
var part1name = someObject["part1"]["name"];
var part2quantity = someObject["part2"]["qty"];
var part3name1 = someObject["part3"][0]["name"];
Both of which will work
Or maybe you are asking for this
var partName = "part1";
var nameStr = "name";
var part1name = someObject[partName][nameStr];
Finally you could be asking for this
var partName = "part1.name";
var partBits = partName.split(".");
var part1name = someObject[partBits[0]][partBits[1]];
I think you are asking for this:
var part1name = someObject.part1.name;
var part2quantity = someObject.part2.qty;
var part3name1 = someObject.part3[0].name;
You could be asking for this:
var part1name = someObject["part1"]["name"];
var part2quantity = someObject["part2"]["qty"];
var part3name1 = someObject["part3"][0]["name"];
Both of which will work
Or maybe you are asking for this
var partName = "part1";
var nameStr = "name";
var part1name = someObject[partName][nameStr];
Finally you could be asking for this
var partName = "part1.name";
var partBits = partName.split(".");
var part1name = someObject[partBits[0]][partBits[1]];
edited Jun 27 '11 at 20:46
answered Jun 27 '11 at 10:28
HoganHogan
54.8k865102
54.8k865102
I think OP's asking for the last solution. However, strings don't haveSplit
method, but rathersplit
.
– duri
Jun 27 '11 at 10:37
Actualy I was asking the last one. The partName variable is filled with string indicating the key-structure to value. Your solution seems makes sense. However I may need to modify for extended depth in the data, like 4-5 level and more. And I am wondering if I can treat the array and object uniformly with this?
– Komaruloh
Jun 27 '11 at 10:38
add a comment |
I think OP's asking for the last solution. However, strings don't haveSplit
method, but rathersplit
.
– duri
Jun 27 '11 at 10:37
Actualy I was asking the last one. The partName variable is filled with string indicating the key-structure to value. Your solution seems makes sense. However I may need to modify for extended depth in the data, like 4-5 level and more. And I am wondering if I can treat the array and object uniformly with this?
– Komaruloh
Jun 27 '11 at 10:38
I think OP's asking for the last solution. However, strings don't have
Split
method, but rather split
.– duri
Jun 27 '11 at 10:37
I think OP's asking for the last solution. However, strings don't have
Split
method, but rather split
.– duri
Jun 27 '11 at 10:37
Actualy I was asking the last one. The partName variable is filled with string indicating the key-structure to value. Your solution seems makes sense. However I may need to modify for extended depth in the data, like 4-5 level and more. And I am wondering if I can treat the array and object uniformly with this?
– Komaruloh
Jun 27 '11 at 10:38
Actualy I was asking the last one. The partName variable is filled with string indicating the key-structure to value. Your solution seems makes sense. However I may need to modify for extended depth in the data, like 4-5 level and more. And I am wondering if I can treat the array and object uniformly with this?
– Komaruloh
Jun 27 '11 at 10:38
add a comment |
Speigg's approach is very neat and clean, though I found this reply while searching for the solution of accessing AngularJS $scope properties by string path and with a little modification it does the job:
$scope.resolve = function( path, obj ) {
return path.split('.').reduce( function( prev, curr ) {
return prev[curr];
}, obj || this );
}
Just place this function in your root controller and use it any child scope like this:
$scope.resolve( 'path.to.any.object.in.scope')
add a comment |
Speigg's approach is very neat and clean, though I found this reply while searching for the solution of accessing AngularJS $scope properties by string path and with a little modification it does the job:
$scope.resolve = function( path, obj ) {
return path.split('.').reduce( function( prev, curr ) {
return prev[curr];
}, obj || this );
}
Just place this function in your root controller and use it any child scope like this:
$scope.resolve( 'path.to.any.object.in.scope')
add a comment |
Speigg's approach is very neat and clean, though I found this reply while searching for the solution of accessing AngularJS $scope properties by string path and with a little modification it does the job:
$scope.resolve = function( path, obj ) {
return path.split('.').reduce( function( prev, curr ) {
return prev[curr];
}, obj || this );
}
Just place this function in your root controller and use it any child scope like this:
$scope.resolve( 'path.to.any.object.in.scope')
Speigg's approach is very neat and clean, though I found this reply while searching for the solution of accessing AngularJS $scope properties by string path and with a little modification it does the job:
$scope.resolve = function( path, obj ) {
return path.split('.').reduce( function( prev, curr ) {
return prev[curr];
}, obj || this );
}
Just place this function in your root controller and use it any child scope like this:
$scope.resolve( 'path.to.any.object.in.scope')
answered Feb 26 '15 at 12:22
nesinervinknesinervink
12818
12818
add a comment |
add a comment |
It's a one liner with lodash.
const deep = { l1: { l2: { l3: "Hello" } } };
const prop = "l1.l2.l3";
const val = _.reduce(prop.split('.'), function(result, value) { return result ? result[value] : undefined; }, deep);
// val === "Hello"
Or even better...
const val = _.get(deep, prop);
Or ES6 version w/ reduce...
const val = prop.split('.').reduce((r, val) => { return r ? r[val] : undefined; }, deep);
Plunkr
add a comment |
It's a one liner with lodash.
const deep = { l1: { l2: { l3: "Hello" } } };
const prop = "l1.l2.l3";
const val = _.reduce(prop.split('.'), function(result, value) { return result ? result[value] : undefined; }, deep);
// val === "Hello"
Or even better...
const val = _.get(deep, prop);
Or ES6 version w/ reduce...
const val = prop.split('.').reduce((r, val) => { return r ? r[val] : undefined; }, deep);
Plunkr
add a comment |
It's a one liner with lodash.
const deep = { l1: { l2: { l3: "Hello" } } };
const prop = "l1.l2.l3";
const val = _.reduce(prop.split('.'), function(result, value) { return result ? result[value] : undefined; }, deep);
// val === "Hello"
Or even better...
const val = _.get(deep, prop);
Or ES6 version w/ reduce...
const val = prop.split('.').reduce((r, val) => { return r ? r[val] : undefined; }, deep);
Plunkr
It's a one liner with lodash.
const deep = { l1: { l2: { l3: "Hello" } } };
const prop = "l1.l2.l3";
const val = _.reduce(prop.split('.'), function(result, value) { return result ? result[value] : undefined; }, deep);
// val === "Hello"
Or even better...
const val = _.get(deep, prop);
Or ES6 version w/ reduce...
const val = prop.split('.').reduce((r, val) => { return r ? r[val] : undefined; }, deep);
Plunkr
edited Nov 18 '17 at 0:50
answered Dec 8 '16 at 16:19
JamesJames
2,4711615
2,4711615
add a comment |
add a comment |
I haven't yet found a package to do all of the operations with a string path, so I ended up writing my own quick little package which supports insert(), get() (with default return), set() and remove() operations.
You can use dot notation, brackets, number indices, string number properties, and keys with non-word characters. Simple usage below:
> var jsocrud = require('jsocrud');
...
// Get (Read) ---
> var obj = {
> foo: [
> {
> 'key w/ non-word chars': 'bar'
> }
> ]
> };
undefined
> jsocrud.get(obj, '.foo[0]["key w/ non-word chars"]');
'bar'
https://www.npmjs.com/package/jsocrud
https://github.com/vertical-knowledge/jsocrud
add a comment |
I haven't yet found a package to do all of the operations with a string path, so I ended up writing my own quick little package which supports insert(), get() (with default return), set() and remove() operations.
You can use dot notation, brackets, number indices, string number properties, and keys with non-word characters. Simple usage below:
> var jsocrud = require('jsocrud');
...
// Get (Read) ---
> var obj = {
> foo: [
> {
> 'key w/ non-word chars': 'bar'
> }
> ]
> };
undefined
> jsocrud.get(obj, '.foo[0]["key w/ non-word chars"]');
'bar'
https://www.npmjs.com/package/jsocrud
https://github.com/vertical-knowledge/jsocrud
add a comment |
I haven't yet found a package to do all of the operations with a string path, so I ended up writing my own quick little package which supports insert(), get() (with default return), set() and remove() operations.
You can use dot notation, brackets, number indices, string number properties, and keys with non-word characters. Simple usage below:
> var jsocrud = require('jsocrud');
...
// Get (Read) ---
> var obj = {
> foo: [
> {
> 'key w/ non-word chars': 'bar'
> }
> ]
> };
undefined
> jsocrud.get(obj, '.foo[0]["key w/ non-word chars"]');
'bar'
https://www.npmjs.com/package/jsocrud
https://github.com/vertical-knowledge/jsocrud
I haven't yet found a package to do all of the operations with a string path, so I ended up writing my own quick little package which supports insert(), get() (with default return), set() and remove() operations.
You can use dot notation, brackets, number indices, string number properties, and keys with non-word characters. Simple usage below:
> var jsocrud = require('jsocrud');
...
// Get (Read) ---
> var obj = {
> foo: [
> {
> 'key w/ non-word chars': 'bar'
> }
> ]
> };
undefined
> jsocrud.get(obj, '.foo[0]["key w/ non-word chars"]');
'bar'
https://www.npmjs.com/package/jsocrud
https://github.com/vertical-knowledge/jsocrud
edited Apr 25 '15 at 1:32
answered Apr 25 '15 at 1:08
KyleKyle
314
314
add a comment |
add a comment |
Simple function, allowing for either a string or array path.
function get(obj, path) {
if(typeof path === 'string') path = path.split('.');
if(path.length === 0) return obj;
return get(obj[path[0]], path.slice(1));
}
const obj = {a: {b: {c: 'foo'}}};
console.log(get(obj, 'a.b.c')); //foo
OR
console.log(get(obj, ['a', 'b', 'c'])); //foo
If you're going to post code as an answer, please explain why the code answers the question.
– Tieson T.
Dec 26 '16 at 5:44
add a comment |
Simple function, allowing for either a string or array path.
function get(obj, path) {
if(typeof path === 'string') path = path.split('.');
if(path.length === 0) return obj;
return get(obj[path[0]], path.slice(1));
}
const obj = {a: {b: {c: 'foo'}}};
console.log(get(obj, 'a.b.c')); //foo
OR
console.log(get(obj, ['a', 'b', 'c'])); //foo
If you're going to post code as an answer, please explain why the code answers the question.
– Tieson T.
Dec 26 '16 at 5:44
add a comment |
Simple function, allowing for either a string or array path.
function get(obj, path) {
if(typeof path === 'string') path = path.split('.');
if(path.length === 0) return obj;
return get(obj[path[0]], path.slice(1));
}
const obj = {a: {b: {c: 'foo'}}};
console.log(get(obj, 'a.b.c')); //foo
OR
console.log(get(obj, ['a', 'b', 'c'])); //foo
Simple function, allowing for either a string or array path.
function get(obj, path) {
if(typeof path === 'string') path = path.split('.');
if(path.length === 0) return obj;
return get(obj[path[0]], path.slice(1));
}
const obj = {a: {b: {c: 'foo'}}};
console.log(get(obj, 'a.b.c')); //foo
OR
console.log(get(obj, ['a', 'b', 'c'])); //foo
edited Dec 26 '16 at 14:42
answered Dec 26 '16 at 4:51
BenBen
1,4171317
1,4171317
If you're going to post code as an answer, please explain why the code answers the question.
– Tieson T.
Dec 26 '16 at 5:44
add a comment |
If you're going to post code as an answer, please explain why the code answers the question.
– Tieson T.
Dec 26 '16 at 5:44
If you're going to post code as an answer, please explain why the code answers the question.
– Tieson T.
Dec 26 '16 at 5:44
If you're going to post code as an answer, please explain why the code answers the question.
– Tieson T.
Dec 26 '16 at 5:44
add a comment |
Just in case, anyone's visiting this question in 2017 or later and looking for an easy-to-remember way, here's an elaborate blog post on Accessing Nested Objects in JavaScript without being bamboozled by
Cannot read property 'foo' of undefined error
Access Nested Objects Using Array Reduce
Let's take this example structure
const user = {
id: 101,
email: 'jack@dev.com',
personalInfo: {
name: 'Jack',
address: [{
line1: 'westwish st',
line2: 'washmasher',
city: 'wallas',
state: 'WX'
}]
}
}
To be able to access nested arrays, you can write your own array reduce util.
const getNestedObject = (nestedObj, pathArr) => {
return pathArr.reduce((obj, key) =>
(obj && obj[key] !== 'undefined') ? obj[key] : undefined, nestedObj);
}
// pass in your object structure as array elements
const name = getNestedObject(user, ['personalInfo', 'name']);
// to access nested array, just pass in array index as an element the path array.
const city = getNestedObject(user, ['personalInfo', 'address', 0, 'city']);
// this will return the city from the first address item.
There is also an excellent type handling minimal library typy that does all this for you.
With typy, your code will look like this
const city = t(user, 'personalInfo.address[0].city').safeObject;
Disclaimer: I am the author of this package.
add a comment |
Just in case, anyone's visiting this question in 2017 or later and looking for an easy-to-remember way, here's an elaborate blog post on Accessing Nested Objects in JavaScript without being bamboozled by
Cannot read property 'foo' of undefined error
Access Nested Objects Using Array Reduce
Let's take this example structure
const user = {
id: 101,
email: 'jack@dev.com',
personalInfo: {
name: 'Jack',
address: [{
line1: 'westwish st',
line2: 'washmasher',
city: 'wallas',
state: 'WX'
}]
}
}
To be able to access nested arrays, you can write your own array reduce util.
const getNestedObject = (nestedObj, pathArr) => {
return pathArr.reduce((obj, key) =>
(obj && obj[key] !== 'undefined') ? obj[key] : undefined, nestedObj);
}
// pass in your object structure as array elements
const name = getNestedObject(user, ['personalInfo', 'name']);
// to access nested array, just pass in array index as an element the path array.
const city = getNestedObject(user, ['personalInfo', 'address', 0, 'city']);
// this will return the city from the first address item.
There is also an excellent type handling minimal library typy that does all this for you.
With typy, your code will look like this
const city = t(user, 'personalInfo.address[0].city').safeObject;
Disclaimer: I am the author of this package.
add a comment |
Just in case, anyone's visiting this question in 2017 or later and looking for an easy-to-remember way, here's an elaborate blog post on Accessing Nested Objects in JavaScript without being bamboozled by
Cannot read property 'foo' of undefined error
Access Nested Objects Using Array Reduce
Let's take this example structure
const user = {
id: 101,
email: 'jack@dev.com',
personalInfo: {
name: 'Jack',
address: [{
line1: 'westwish st',
line2: 'washmasher',
city: 'wallas',
state: 'WX'
}]
}
}
To be able to access nested arrays, you can write your own array reduce util.
const getNestedObject = (nestedObj, pathArr) => {
return pathArr.reduce((obj, key) =>
(obj && obj[key] !== 'undefined') ? obj[key] : undefined, nestedObj);
}
// pass in your object structure as array elements
const name = getNestedObject(user, ['personalInfo', 'name']);
// to access nested array, just pass in array index as an element the path array.
const city = getNestedObject(user, ['personalInfo', 'address', 0, 'city']);
// this will return the city from the first address item.
There is also an excellent type handling minimal library typy that does all this for you.
With typy, your code will look like this
const city = t(user, 'personalInfo.address[0].city').safeObject;
Disclaimer: I am the author of this package.
Just in case, anyone's visiting this question in 2017 or later and looking for an easy-to-remember way, here's an elaborate blog post on Accessing Nested Objects in JavaScript without being bamboozled by
Cannot read property 'foo' of undefined error
Access Nested Objects Using Array Reduce
Let's take this example structure
const user = {
id: 101,
email: 'jack@dev.com',
personalInfo: {
name: 'Jack',
address: [{
line1: 'westwish st',
line2: 'washmasher',
city: 'wallas',
state: 'WX'
}]
}
}
To be able to access nested arrays, you can write your own array reduce util.
const getNestedObject = (nestedObj, pathArr) => {
return pathArr.reduce((obj, key) =>
(obj && obj[key] !== 'undefined') ? obj[key] : undefined, nestedObj);
}
// pass in your object structure as array elements
const name = getNestedObject(user, ['personalInfo', 'name']);
// to access nested array, just pass in array index as an element the path array.
const city = getNestedObject(user, ['personalInfo', 'address', 0, 'city']);
// this will return the city from the first address item.
There is also an excellent type handling minimal library typy that does all this for you.
With typy, your code will look like this
const city = t(user, 'personalInfo.address[0].city').safeObject;
Disclaimer: I am the author of this package.
answered Jul 8 '18 at 13:01
Dinesh PandiyanDinesh Pandiyan
2,495925
2,495925
add a comment |
add a comment |
There is an npm
module now for doing this: https://github.com/erictrinh/safe-access
Example usage:
var access = require('safe-access');
access(very, 'nested.property.and.array[0]');
add a comment |
There is an npm
module now for doing this: https://github.com/erictrinh/safe-access
Example usage:
var access = require('safe-access');
access(very, 'nested.property.and.array[0]');
add a comment |
There is an npm
module now for doing this: https://github.com/erictrinh/safe-access
Example usage:
var access = require('safe-access');
access(very, 'nested.property.and.array[0]');
There is an npm
module now for doing this: https://github.com/erictrinh/safe-access
Example usage:
var access = require('safe-access');
access(very, 'nested.property.and.array[0]');
answered Jun 13 '14 at 18:56
calebcaleb
1,3751420
1,3751420
add a comment |
add a comment |
/**
* Access a deep value inside a object
* Works by passing a path like "foo.bar", also works with nested arrays like "foo[0][1].baz"
* @author Victor B. https://gist.github.com/victornpb/4c7882c1b9d36292308e
* Unit tests: http://jsfiddle.net/Victornpb/0u1qygrh/
*/
function getDeepVal(obj, path) {
if (typeof obj === "undefined" || obj === null) return;
path = path.split(/[.[]"']{1,2}/);
for (var i = 0, l = path.length; i < l; i++) {
if (path[i] === "") continue;
obj = obj[path[i]];
if (typeof obj === "undefined" || obj === null) return;
}
return obj;
}
Works with
getDeepVal(obj,'foo.bar')
getDeepVal(obj,'foo.1.bar')
getDeepVal(obj,'foo[0].baz')
getDeepVal(obj,'foo[1][2]')
getDeepVal(obj,"foo['bar'].baz")
getDeepVal(obj,"foo['bar']['baz']")
getDeepVal(obj,"foo.bar.0.baz[1]['2']['w'].aaa["f"].bb")
add a comment |
/**
* Access a deep value inside a object
* Works by passing a path like "foo.bar", also works with nested arrays like "foo[0][1].baz"
* @author Victor B. https://gist.github.com/victornpb/4c7882c1b9d36292308e
* Unit tests: http://jsfiddle.net/Victornpb/0u1qygrh/
*/
function getDeepVal(obj, path) {
if (typeof obj === "undefined" || obj === null) return;
path = path.split(/[.[]"']{1,2}/);
for (var i = 0, l = path.length; i < l; i++) {
if (path[i] === "") continue;
obj = obj[path[i]];
if (typeof obj === "undefined" || obj === null) return;
}
return obj;
}
Works with
getDeepVal(obj,'foo.bar')
getDeepVal(obj,'foo.1.bar')
getDeepVal(obj,'foo[0].baz')
getDeepVal(obj,'foo[1][2]')
getDeepVal(obj,"foo['bar'].baz")
getDeepVal(obj,"foo['bar']['baz']")
getDeepVal(obj,"foo.bar.0.baz[1]['2']['w'].aaa["f"].bb")
add a comment |
/**
* Access a deep value inside a object
* Works by passing a path like "foo.bar", also works with nested arrays like "foo[0][1].baz"
* @author Victor B. https://gist.github.com/victornpb/4c7882c1b9d36292308e
* Unit tests: http://jsfiddle.net/Victornpb/0u1qygrh/
*/
function getDeepVal(obj, path) {
if (typeof obj === "undefined" || obj === null) return;
path = path.split(/[.[]"']{1,2}/);
for (var i = 0, l = path.length; i < l; i++) {
if (path[i] === "") continue;
obj = obj[path[i]];
if (typeof obj === "undefined" || obj === null) return;
}
return obj;
}
Works with
getDeepVal(obj,'foo.bar')
getDeepVal(obj,'foo.1.bar')
getDeepVal(obj,'foo[0].baz')
getDeepVal(obj,'foo[1][2]')
getDeepVal(obj,"foo['bar'].baz")
getDeepVal(obj,"foo['bar']['baz']")
getDeepVal(obj,"foo.bar.0.baz[1]['2']['w'].aaa["f"].bb")
/**
* Access a deep value inside a object
* Works by passing a path like "foo.bar", also works with nested arrays like "foo[0][1].baz"
* @author Victor B. https://gist.github.com/victornpb/4c7882c1b9d36292308e
* Unit tests: http://jsfiddle.net/Victornpb/0u1qygrh/
*/
function getDeepVal(obj, path) {
if (typeof obj === "undefined" || obj === null) return;
path = path.split(/[.[]"']{1,2}/);
for (var i = 0, l = path.length; i < l; i++) {
if (path[i] === "") continue;
obj = obj[path[i]];
if (typeof obj === "undefined" || obj === null) return;
}
return obj;
}
Works with
getDeepVal(obj,'foo.bar')
getDeepVal(obj,'foo.1.bar')
getDeepVal(obj,'foo[0].baz')
getDeepVal(obj,'foo[1][2]')
getDeepVal(obj,"foo['bar'].baz")
getDeepVal(obj,"foo['bar']['baz']")
getDeepVal(obj,"foo.bar.0.baz[1]['2']['w'].aaa["f"].bb")
edited Sep 29 '16 at 19:51
answered Mar 1 '16 at 17:05
Vitim.usVitim.us
9,81696280
9,81696280
add a comment |
add a comment |
While reduce is good, I am surprised no one used forEach:
function valueForKeyPath(obj, path){
const keys = path.split('.');
keys.forEach((key)=> obj = obj[key]);
return obj;
};
Test
You are not even checking if obj[key] actually exists. It's unreliable.
– Carles Alcolea
Jul 22 '18 at 4:08
@CarlesAlcolea by default js will neither check if the key of an object exists:a.b.c
will raise an exception if there is no propertyb
in your object. If you need something silently dismissing the wrong keypath (which I do not recommend), you can still replace the forEach with this onekeys.forEach((key)=> obj = (obj||{})[key]);
– Flavien Volken
Jul 23 '18 at 7:57
I run through it an object that was missing a curly brace, my bad :)
– Carles Alcolea
Jul 28 '18 at 23:59
add a comment |
While reduce is good, I am surprised no one used forEach:
function valueForKeyPath(obj, path){
const keys = path.split('.');
keys.forEach((key)=> obj = obj[key]);
return obj;
};
Test
You are not even checking if obj[key] actually exists. It's unreliable.
– Carles Alcolea
Jul 22 '18 at 4:08
@CarlesAlcolea by default js will neither check if the key of an object exists:a.b.c
will raise an exception if there is no propertyb
in your object. If you need something silently dismissing the wrong keypath (which I do not recommend), you can still replace the forEach with this onekeys.forEach((key)=> obj = (obj||{})[key]);
– Flavien Volken
Jul 23 '18 at 7:57
I run through it an object that was missing a curly brace, my bad :)
– Carles Alcolea
Jul 28 '18 at 23:59
add a comment |
While reduce is good, I am surprised no one used forEach:
function valueForKeyPath(obj, path){
const keys = path.split('.');
keys.forEach((key)=> obj = obj[key]);
return obj;
};
Test
While reduce is good, I am surprised no one used forEach:
function valueForKeyPath(obj, path){
const keys = path.split('.');
keys.forEach((key)=> obj = obj[key]);
return obj;
};
Test
edited Dec 15 '17 at 14:03
answered Dec 15 '17 at 13:54
Flavien VolkenFlavien Volken
9,41765575
9,41765575
You are not even checking if obj[key] actually exists. It's unreliable.
– Carles Alcolea
Jul 22 '18 at 4:08
@CarlesAlcolea by default js will neither check if the key of an object exists:a.b.c
will raise an exception if there is no propertyb
in your object. If you need something silently dismissing the wrong keypath (which I do not recommend), you can still replace the forEach with this onekeys.forEach((key)=> obj = (obj||{})[key]);
– Flavien Volken
Jul 23 '18 at 7:57
I run through it an object that was missing a curly brace, my bad :)
– Carles Alcolea
Jul 28 '18 at 23:59
add a comment |
You are not even checking if obj[key] actually exists. It's unreliable.
– Carles Alcolea
Jul 22 '18 at 4:08
@CarlesAlcolea by default js will neither check if the key of an object exists:a.b.c
will raise an exception if there is no propertyb
in your object. If you need something silently dismissing the wrong keypath (which I do not recommend), you can still replace the forEach with this onekeys.forEach((key)=> obj = (obj||{})[key]);
– Flavien Volken
Jul 23 '18 at 7:57
I run through it an object that was missing a curly brace, my bad :)
– Carles Alcolea
Jul 28 '18 at 23:59
You are not even checking if obj[key] actually exists. It's unreliable.
– Carles Alcolea
Jul 22 '18 at 4:08
You are not even checking if obj[key] actually exists. It's unreliable.
– Carles Alcolea
Jul 22 '18 at 4:08
@CarlesAlcolea by default js will neither check if the key of an object exists:
a.b.c
will raise an exception if there is no property b
in your object. If you need something silently dismissing the wrong keypath (which I do not recommend), you can still replace the forEach with this one keys.forEach((key)=> obj = (obj||{})[key]);
– Flavien Volken
Jul 23 '18 at 7:57
@CarlesAlcolea by default js will neither check if the key of an object exists:
a.b.c
will raise an exception if there is no property b
in your object. If you need something silently dismissing the wrong keypath (which I do not recommend), you can still replace the forEach with this one keys.forEach((key)=> obj = (obj||{})[key]);
– Flavien Volken
Jul 23 '18 at 7:57
I run through it an object that was missing a curly brace, my bad :)
– Carles Alcolea
Jul 28 '18 at 23:59
I run through it an object that was missing a curly brace, my bad :)
– Carles Alcolea
Jul 28 '18 at 23:59
add a comment |
If you need to access different nested key without knowing it at coding time (it will be trivial to address them) you can use the array notation accessor:
var part1name = someObject['part1']['name'];
var part2quantity = someObject['part2']['qty'];
var part3name1 = someObject['part3'][0]['name'];
They are equivalent to the dot notation accessor and may vary at runtime, for example:
var part = 'part1';
var property = 'name';
var part1name = someObject[part][property];
is equivalent to
var part1name = someObject['part1']['name'];
or
var part1name = someObject.part1.name;
I hope this address your question...
EDIT
I won't use a string to mantain a sort of xpath query to access an object value.
As you have to call a function to parse the query and retrieve the value I would follow another path (not :
var part1name = function(){ return this.part1.name; }
var part2quantity = function() { return this['part2']['qty']; }
var part3name1 = function() { return this.part3[0]['name'];}
// usage: part1name.apply(someObject);
or, if you are uneasy with the apply method
var part1name = function(obj){ return obj.part1.name; }
var part2quantity = function(obj) { return obj['part2']['qty']; }
var part3name1 = function(obj) { return obj.part3[0]['name'];}
// usage: part1name(someObject);
The functions are shorter, clearer, the interpreter check them for you for syntax errors and so on.
By the way, I feel that a simple assignment made at right time will be sufficent...
Interesting. But in my case, the someObject is initialize yet when I assign value to part1name. I only know the structure. That is why I use string to describe the structure. And hoping to be able to use it to query my data from someObject. Thanks for sharing your thought. :)
– Komaruloh
Jun 27 '11 at 10:47
@Komaruloh : I think you would write that the object is NOT initialized yet when you create your variables. By the way I don't get the point, why can't you do the assignment at appropriate time?
– Eineki
Jun 27 '11 at 11:24
Sorry about not mentioning that someObject is not initialized yet. As for the reason, someObject is fetch via web service. And I want to have an array of header which consist of part1name, part2qty, etc. So that I could just loop through the header array and get the value I wanted based on part1name value as the 'key'/path to someObject.
– Komaruloh
Jun 27 '11 at 11:47
add a comment |
If you need to access different nested key without knowing it at coding time (it will be trivial to address them) you can use the array notation accessor:
var part1name = someObject['part1']['name'];
var part2quantity = someObject['part2']['qty'];
var part3name1 = someObject['part3'][0]['name'];
They are equivalent to the dot notation accessor and may vary at runtime, for example:
var part = 'part1';
var property = 'name';
var part1name = someObject[part][property];
is equivalent to
var part1name = someObject['part1']['name'];
or
var part1name = someObject.part1.name;
I hope this address your question...
EDIT
I won't use a string to mantain a sort of xpath query to access an object value.
As you have to call a function to parse the query and retrieve the value I would follow another path (not :
var part1name = function(){ return this.part1.name; }
var part2quantity = function() { return this['part2']['qty']; }
var part3name1 = function() { return this.part3[0]['name'];}
// usage: part1name.apply(someObject);
or, if you are uneasy with the apply method
var part1name = function(obj){ return obj.part1.name; }
var part2quantity = function(obj) { return obj['part2']['qty']; }
var part3name1 = function(obj) { return obj.part3[0]['name'];}
// usage: part1name(someObject);
The functions are shorter, clearer, the interpreter check them for you for syntax errors and so on.
By the way, I feel that a simple assignment made at right time will be sufficent...
Interesting. But in my case, the someObject is initialize yet when I assign value to part1name. I only know the structure. That is why I use string to describe the structure. And hoping to be able to use it to query my data from someObject. Thanks for sharing your thought. :)
– Komaruloh
Jun 27 '11 at 10:47
@Komaruloh : I think you would write that the object is NOT initialized yet when you create your variables. By the way I don't get the point, why can't you do the assignment at appropriate time?
– Eineki
Jun 27 '11 at 11:24
Sorry about not mentioning that someObject is not initialized yet. As for the reason, someObject is fetch via web service. And I want to have an array of header which consist of part1name, part2qty, etc. So that I could just loop through the header array and get the value I wanted based on part1name value as the 'key'/path to someObject.
– Komaruloh
Jun 27 '11 at 11:47
add a comment |
If you need to access different nested key without knowing it at coding time (it will be trivial to address them) you can use the array notation accessor:
var part1name = someObject['part1']['name'];
var part2quantity = someObject['part2']['qty'];
var part3name1 = someObject['part3'][0]['name'];
They are equivalent to the dot notation accessor and may vary at runtime, for example:
var part = 'part1';
var property = 'name';
var part1name = someObject[part][property];
is equivalent to
var part1name = someObject['part1']['name'];
or
var part1name = someObject.part1.name;
I hope this address your question...
EDIT
I won't use a string to mantain a sort of xpath query to access an object value.
As you have to call a function to parse the query and retrieve the value I would follow another path (not :
var part1name = function(){ return this.part1.name; }
var part2quantity = function() { return this['part2']['qty']; }
var part3name1 = function() { return this.part3[0]['name'];}
// usage: part1name.apply(someObject);
or, if you are uneasy with the apply method
var part1name = function(obj){ return obj.part1.name; }
var part2quantity = function(obj) { return obj['part2']['qty']; }
var part3name1 = function(obj) { return obj.part3[0]['name'];}
// usage: part1name(someObject);
The functions are shorter, clearer, the interpreter check them for you for syntax errors and so on.
By the way, I feel that a simple assignment made at right time will be sufficent...
If you need to access different nested key without knowing it at coding time (it will be trivial to address them) you can use the array notation accessor:
var part1name = someObject['part1']['name'];
var part2quantity = someObject['part2']['qty'];
var part3name1 = someObject['part3'][0]['name'];
They are equivalent to the dot notation accessor and may vary at runtime, for example:
var part = 'part1';
var property = 'name';
var part1name = someObject[part][property];
is equivalent to
var part1name = someObject['part1']['name'];
or
var part1name = someObject.part1.name;
I hope this address your question...
EDIT
I won't use a string to mantain a sort of xpath query to access an object value.
As you have to call a function to parse the query and retrieve the value I would follow another path (not :
var part1name = function(){ return this.part1.name; }
var part2quantity = function() { return this['part2']['qty']; }
var part3name1 = function() { return this.part3[0]['name'];}
// usage: part1name.apply(someObject);
or, if you are uneasy with the apply method
var part1name = function(obj){ return obj.part1.name; }
var part2quantity = function(obj) { return obj['part2']['qty']; }
var part3name1 = function(obj) { return obj.part3[0]['name'];}
// usage: part1name(someObject);
The functions are shorter, clearer, the interpreter check them for you for syntax errors and so on.
By the way, I feel that a simple assignment made at right time will be sufficent...
edited Jun 27 '11 at 11:35
answered Jun 27 '11 at 10:36
EinekiEineki
12.7k53751
12.7k53751
Interesting. But in my case, the someObject is initialize yet when I assign value to part1name. I only know the structure. That is why I use string to describe the structure. And hoping to be able to use it to query my data from someObject. Thanks for sharing your thought. :)
– Komaruloh
Jun 27 '11 at 10:47
@Komaruloh : I think you would write that the object is NOT initialized yet when you create your variables. By the way I don't get the point, why can't you do the assignment at appropriate time?
– Eineki
Jun 27 '11 at 11:24
Sorry about not mentioning that someObject is not initialized yet. As for the reason, someObject is fetch via web service. And I want to have an array of header which consist of part1name, part2qty, etc. So that I could just loop through the header array and get the value I wanted based on part1name value as the 'key'/path to someObject.
– Komaruloh
Jun 27 '11 at 11:47
add a comment |
Interesting. But in my case, the someObject is initialize yet when I assign value to part1name. I only know the structure. That is why I use string to describe the structure. And hoping to be able to use it to query my data from someObject. Thanks for sharing your thought. :)
– Komaruloh
Jun 27 '11 at 10:47
@Komaruloh : I think you would write that the object is NOT initialized yet when you create your variables. By the way I don't get the point, why can't you do the assignment at appropriate time?
– Eineki
Jun 27 '11 at 11:24
Sorry about not mentioning that someObject is not initialized yet. As for the reason, someObject is fetch via web service. And I want to have an array of header which consist of part1name, part2qty, etc. So that I could just loop through the header array and get the value I wanted based on part1name value as the 'key'/path to someObject.
– Komaruloh
Jun 27 '11 at 11:47
Interesting. But in my case, the someObject is initialize yet when I assign value to part1name. I only know the structure. That is why I use string to describe the structure. And hoping to be able to use it to query my data from someObject. Thanks for sharing your thought. :)
– Komaruloh
Jun 27 '11 at 10:47
Interesting. But in my case, the someObject is initialize yet when I assign value to part1name. I only know the structure. That is why I use string to describe the structure. And hoping to be able to use it to query my data from someObject. Thanks for sharing your thought. :)
– Komaruloh
Jun 27 '11 at 10:47
@Komaruloh : I think you would write that the object is NOT initialized yet when you create your variables. By the way I don't get the point, why can't you do the assignment at appropriate time?
– Eineki
Jun 27 '11 at 11:24
@Komaruloh : I think you would write that the object is NOT initialized yet when you create your variables. By the way I don't get the point, why can't you do the assignment at appropriate time?
– Eineki
Jun 27 '11 at 11:24
Sorry about not mentioning that someObject is not initialized yet. As for the reason, someObject is fetch via web service. And I want to have an array of header which consist of part1name, part2qty, etc. So that I could just loop through the header array and get the value I wanted based on part1name value as the 'key'/path to someObject.
– Komaruloh
Jun 27 '11 at 11:47
Sorry about not mentioning that someObject is not initialized yet. As for the reason, someObject is fetch via web service. And I want to have an array of header which consist of part1name, part2qty, etc. So that I could just loop through the header array and get the value I wanted based on part1name value as the 'key'/path to someObject.
– Komaruloh
Jun 27 '11 at 11:47
add a comment |
Just had the same question recently and successfully used https://npmjs.org/package/tea-properties which also set
nested object/arrays :
get:
var o = {
prop: {
arr: [
{foo: 'bar'}
]
}
};
var properties = require('tea-properties');
var value = properties.get(o, 'prop.arr[0].foo');
assert(value, 'bar'); // true
set:
var o = {};
var properties = require('tea-properties');
properties.set(o, 'prop.arr[0].foo', 'bar');
assert(o.prop.arr[0].foo, 'bar'); // true
"This module has been discontinued. Use chaijs/pathval."
– Patrick Fisher
Mar 18 '14 at 0:09
add a comment |
Just had the same question recently and successfully used https://npmjs.org/package/tea-properties which also set
nested object/arrays :
get:
var o = {
prop: {
arr: [
{foo: 'bar'}
]
}
};
var properties = require('tea-properties');
var value = properties.get(o, 'prop.arr[0].foo');
assert(value, 'bar'); // true
set:
var o = {};
var properties = require('tea-properties');
properties.set(o, 'prop.arr[0].foo', 'bar');
assert(o.prop.arr[0].foo, 'bar'); // true
"This module has been discontinued. Use chaijs/pathval."
– Patrick Fisher
Mar 18 '14 at 0:09
add a comment |
Just had the same question recently and successfully used https://npmjs.org/package/tea-properties which also set
nested object/arrays :
get:
var o = {
prop: {
arr: [
{foo: 'bar'}
]
}
};
var properties = require('tea-properties');
var value = properties.get(o, 'prop.arr[0].foo');
assert(value, 'bar'); // true
set:
var o = {};
var properties = require('tea-properties');
properties.set(o, 'prop.arr[0].foo', 'bar');
assert(o.prop.arr[0].foo, 'bar'); // true
Just had the same question recently and successfully used https://npmjs.org/package/tea-properties which also set
nested object/arrays :
get:
var o = {
prop: {
arr: [
{foo: 'bar'}
]
}
};
var properties = require('tea-properties');
var value = properties.get(o, 'prop.arr[0].foo');
assert(value, 'bar'); // true
set:
var o = {};
var properties = require('tea-properties');
properties.set(o, 'prop.arr[0].foo', 'bar');
assert(o.prop.arr[0].foo, 'bar'); // true
edited Nov 4 '13 at 0:41
answered Oct 25 '13 at 19:33
abernierabernier
13.2k156693
13.2k156693
"This module has been discontinued. Use chaijs/pathval."
– Patrick Fisher
Mar 18 '14 at 0:09
add a comment |
"This module has been discontinued. Use chaijs/pathval."
– Patrick Fisher
Mar 18 '14 at 0:09
"This module has been discontinued. Use chaijs/pathval."
– Patrick Fisher
Mar 18 '14 at 0:09
"This module has been discontinued. Use chaijs/pathval."
– Patrick Fisher
Mar 18 '14 at 0:09
add a comment |
The solutions here are just for accessing the deeply nested keys. I needed one for accessing, adding, modifying and deleting the keys. This is what I came up with:
var deepAccessObject = function(object, path_to_key, type_of_function, value){
switch(type_of_function){
//Add key/modify key
case 0:
if(path_to_key.length === 1){
if(value)
object[path_to_key[0]] = value;
return object[path_to_key[0]];
}else{
if(object[path_to_key[0]])
return deepAccessObject(object[path_to_key[0]], path_to_key.slice(1), type_of_function, value);
else
object[path_to_key[0]] = {};
}
break;
//delete key
case 1:
if(path_to_key.length === 1){
delete object[path_to_key[0]];
return true;
}else{
if(object[path_to_key[0]])
return deepAccessObject(object[path_to_key[0]], path_to_key.slice(1), type_of_function, value);
else
return false;
}
break;
default:
console.log("Wrong type of function");
}
};
path_to_key
: path in an array. You can replace it by yourstring_path.split(".")
.
type_of_function
: 0 for accessing(dont pass any value tovalue
), 0 for add and modify. 1 for delete.
add a comment |
The solutions here are just for accessing the deeply nested keys. I needed one for accessing, adding, modifying and deleting the keys. This is what I came up with:
var deepAccessObject = function(object, path_to_key, type_of_function, value){
switch(type_of_function){
//Add key/modify key
case 0:
if(path_to_key.length === 1){
if(value)
object[path_to_key[0]] = value;
return object[path_to_key[0]];
}else{
if(object[path_to_key[0]])
return deepAccessObject(object[path_to_key[0]], path_to_key.slice(1), type_of_function, value);
else
object[path_to_key[0]] = {};
}
break;
//delete key
case 1:
if(path_to_key.length === 1){
delete object[path_to_key[0]];
return true;
}else{
if(object[path_to_key[0]])
return deepAccessObject(object[path_to_key[0]], path_to_key.slice(1), type_of_function, value);
else
return false;
}
break;
default:
console.log("Wrong type of function");
}
};
path_to_key
: path in an array. You can replace it by yourstring_path.split(".")
.
type_of_function
: 0 for accessing(dont pass any value tovalue
), 0 for add and modify. 1 for delete.
add a comment |
The solutions here are just for accessing the deeply nested keys. I needed one for accessing, adding, modifying and deleting the keys. This is what I came up with:
var deepAccessObject = function(object, path_to_key, type_of_function, value){
switch(type_of_function){
//Add key/modify key
case 0:
if(path_to_key.length === 1){
if(value)
object[path_to_key[0]] = value;
return object[path_to_key[0]];
}else{
if(object[path_to_key[0]])
return deepAccessObject(object[path_to_key[0]], path_to_key.slice(1), type_of_function, value);
else
object[path_to_key[0]] = {};
}
break;
//delete key
case 1:
if(path_to_key.length === 1){
delete object[path_to_key[0]];
return true;
}else{
if(object[path_to_key[0]])
return deepAccessObject(object[path_to_key[0]], path_to_key.slice(1), type_of_function, value);
else
return false;
}
break;
default:
console.log("Wrong type of function");
}
};
path_to_key
: path in an array. You can replace it by yourstring_path.split(".")
.
type_of_function
: 0 for accessing(dont pass any value tovalue
), 0 for add and modify. 1 for delete.
The solutions here are just for accessing the deeply nested keys. I needed one for accessing, adding, modifying and deleting the keys. This is what I came up with:
var deepAccessObject = function(object, path_to_key, type_of_function, value){
switch(type_of_function){
//Add key/modify key
case 0:
if(path_to_key.length === 1){
if(value)
object[path_to_key[0]] = value;
return object[path_to_key[0]];
}else{
if(object[path_to_key[0]])
return deepAccessObject(object[path_to_key[0]], path_to_key.slice(1), type_of_function, value);
else
object[path_to_key[0]] = {};
}
break;
//delete key
case 1:
if(path_to_key.length === 1){
delete object[path_to_key[0]];
return true;
}else{
if(object[path_to_key[0]])
return deepAccessObject(object[path_to_key[0]], path_to_key.slice(1), type_of_function, value);
else
return false;
}
break;
default:
console.log("Wrong type of function");
}
};
path_to_key
: path in an array. You can replace it by yourstring_path.split(".")
.
type_of_function
: 0 for accessing(dont pass any value tovalue
), 0 for add and modify. 1 for delete.
answered Jun 23 '16 at 9:45
ayushgpayushgp
2,16832146
2,16832146
add a comment |
add a comment |
Instead of a string an array can be used adressing nested objects and arrays e.g.: ["my_field", "another_field", 0, "last_field", 10]
Here is an example that would change a field based on this array representation. I am using something like that in react.js for controlled input fields that change the state of nested structures.
let state = {
test: "test_value",
nested: {
level1: "level1 value"
},
arr: [1, 2, 3],
nested_arr: {
arr: ["buh", "bah", "foo"]
}
}
function handleChange(value, fields) {
let update_field = state;
for(var i = 0; i < fields.length - 1; i++){
update_field = update_field[fields[i]];
}
update_field[fields[fields.length-1]] = value;
}
handleChange("update", ["test"]);
handleChange("update_nested", ["nested","level1"]);
handleChange(100, ["arr",0]);
handleChange('changed_foo', ["nested_arr", "arr", 3]);
console.log(state);
add a comment |
Instead of a string an array can be used adressing nested objects and arrays e.g.: ["my_field", "another_field", 0, "last_field", 10]
Here is an example that would change a field based on this array representation. I am using something like that in react.js for controlled input fields that change the state of nested structures.
let state = {
test: "test_value",
nested: {
level1: "level1 value"
},
arr: [1, 2, 3],
nested_arr: {
arr: ["buh", "bah", "foo"]
}
}
function handleChange(value, fields) {
let update_field = state;
for(var i = 0; i < fields.length - 1; i++){
update_field = update_field[fields[i]];
}
update_field[fields[fields.length-1]] = value;
}
handleChange("update", ["test"]);
handleChange("update_nested", ["nested","level1"]);
handleChange(100, ["arr",0]);
handleChange('changed_foo', ["nested_arr", "arr", 3]);
console.log(state);
add a comment |
Instead of a string an array can be used adressing nested objects and arrays e.g.: ["my_field", "another_field", 0, "last_field", 10]
Here is an example that would change a field based on this array representation. I am using something like that in react.js for controlled input fields that change the state of nested structures.
let state = {
test: "test_value",
nested: {
level1: "level1 value"
},
arr: [1, 2, 3],
nested_arr: {
arr: ["buh", "bah", "foo"]
}
}
function handleChange(value, fields) {
let update_field = state;
for(var i = 0; i < fields.length - 1; i++){
update_field = update_field[fields[i]];
}
update_field[fields[fields.length-1]] = value;
}
handleChange("update", ["test"]);
handleChange("update_nested", ["nested","level1"]);
handleChange(100, ["arr",0]);
handleChange('changed_foo', ["nested_arr", "arr", 3]);
console.log(state);
Instead of a string an array can be used adressing nested objects and arrays e.g.: ["my_field", "another_field", 0, "last_field", 10]
Here is an example that would change a field based on this array representation. I am using something like that in react.js for controlled input fields that change the state of nested structures.
let state = {
test: "test_value",
nested: {
level1: "level1 value"
},
arr: [1, 2, 3],
nested_arr: {
arr: ["buh", "bah", "foo"]
}
}
function handleChange(value, fields) {
let update_field = state;
for(var i = 0; i < fields.length - 1; i++){
update_field = update_field[fields[i]];
}
update_field[fields[fields.length-1]] = value;
}
handleChange("update", ["test"]);
handleChange("update_nested", ["nested","level1"]);
handleChange(100, ["arr",0]);
handleChange('changed_foo', ["nested_arr", "arr", 3]);
console.log(state);
answered Oct 25 '17 at 8:12
JodoJodo
1,42611431
1,42611431
add a comment |
add a comment |
Based on a previous answer, I have created a function that can also handle brackets. But no dots inside them due to the split.
function get(obj, str) {
return str.split(/.|[/g).map(function(crumb) {
return crumb.replace(/]$/, '').trim().replace(/^(["'])((?:(?!1)[^\]|\.)*?)1$/, (match, quote, str) => str.replace(/\(\)?/g, "$1"));
}).reduce(function(obj, prop) {
return obj ? obj[prop] : undefined;
}, obj);
}
add a comment |
Based on a previous answer, I have created a function that can also handle brackets. But no dots inside them due to the split.
function get(obj, str) {
return str.split(/.|[/g).map(function(crumb) {
return crumb.replace(/]$/, '').trim().replace(/^(["'])((?:(?!1)[^\]|\.)*?)1$/, (match, quote, str) => str.replace(/\(\)?/g, "$1"));
}).reduce(function(obj, prop) {
return obj ? obj[prop] : undefined;
}, obj);
}
add a comment |
Based on a previous answer, I have created a function that can also handle brackets. But no dots inside them due to the split.
function get(obj, str) {
return str.split(/.|[/g).map(function(crumb) {
return crumb.replace(/]$/, '').trim().replace(/^(["'])((?:(?!1)[^\]|\.)*?)1$/, (match, quote, str) => str.replace(/\(\)?/g, "$1"));
}).reduce(function(obj, prop) {
return obj ? obj[prop] : undefined;
}, obj);
}
Based on a previous answer, I have created a function that can also handle brackets. But no dots inside them due to the split.
function get(obj, str) {
return str.split(/.|[/g).map(function(crumb) {
return crumb.replace(/]$/, '').trim().replace(/^(["'])((?:(?!1)[^\]|\.)*?)1$/, (match, quote, str) => str.replace(/\(\)?/g, "$1"));
}).reduce(function(obj, prop) {
return obj ? obj[prop] : undefined;
}, obj);
}
answered Nov 1 '17 at 12:44
VincentVincent
1,3571018
1,3571018
add a comment |
add a comment |
// (IE9+) Two steps
var pathString = "[0]['property'].others[3].next['final']";
var obj = [{
property: {
others: [1, 2, 3, {
next: {
final: "SUCCESS"
}
}]
}
}];
// Turn string to path array
var pathArray = pathString
.replace(/[["']?([w]+)["']?]/g,".$1")
.split(".")
.splice(1);
// Add object prototype method
Object.prototype.path = function (path) {
try {
return [this].concat(path).reduce(function (f, l) {
return f[l];
});
} catch (e) {
console.error(e);
}
};
// usage
console.log(obj.path(pathArray));
console.log(obj.path([0,"doesNotExist"]));
add a comment |
// (IE9+) Two steps
var pathString = "[0]['property'].others[3].next['final']";
var obj = [{
property: {
others: [1, 2, 3, {
next: {
final: "SUCCESS"
}
}]
}
}];
// Turn string to path array
var pathArray = pathString
.replace(/[["']?([w]+)["']?]/g,".$1")
.split(".")
.splice(1);
// Add object prototype method
Object.prototype.path = function (path) {
try {
return [this].concat(path).reduce(function (f, l) {
return f[l];
});
} catch (e) {
console.error(e);
}
};
// usage
console.log(obj.path(pathArray));
console.log(obj.path([0,"doesNotExist"]));
add a comment |
// (IE9+) Two steps
var pathString = "[0]['property'].others[3].next['final']";
var obj = [{
property: {
others: [1, 2, 3, {
next: {
final: "SUCCESS"
}
}]
}
}];
// Turn string to path array
var pathArray = pathString
.replace(/[["']?([w]+)["']?]/g,".$1")
.split(".")
.splice(1);
// Add object prototype method
Object.prototype.path = function (path) {
try {
return [this].concat(path).reduce(function (f, l) {
return f[l];
});
} catch (e) {
console.error(e);
}
};
// usage
console.log(obj.path(pathArray));
console.log(obj.path([0,"doesNotExist"]));
// (IE9+) Two steps
var pathString = "[0]['property'].others[3].next['final']";
var obj = [{
property: {
others: [1, 2, 3, {
next: {
final: "SUCCESS"
}
}]
}
}];
// Turn string to path array
var pathArray = pathString
.replace(/[["']?([w]+)["']?]/g,".$1")
.split(".")
.splice(1);
// Add object prototype method
Object.prototype.path = function (path) {
try {
return [this].concat(path).reduce(function (f, l) {
return f[l];
});
} catch (e) {
console.error(e);
}
};
// usage
console.log(obj.path(pathArray));
console.log(obj.path([0,"doesNotExist"]));
// (IE9+) Two steps
var pathString = "[0]['property'].others[3].next['final']";
var obj = [{
property: {
others: [1, 2, 3, {
next: {
final: "SUCCESS"
}
}]
}
}];
// Turn string to path array
var pathArray = pathString
.replace(/[["']?([w]+)["']?]/g,".$1")
.split(".")
.splice(1);
// Add object prototype method
Object.prototype.path = function (path) {
try {
return [this].concat(path).reduce(function (f, l) {
return f[l];
});
} catch (e) {
console.error(e);
}
};
// usage
console.log(obj.path(pathArray));
console.log(obj.path([0,"doesNotExist"]));
// (IE9+) Two steps
var pathString = "[0]['property'].others[3].next['final']";
var obj = [{
property: {
others: [1, 2, 3, {
next: {
final: "SUCCESS"
}
}]
}
}];
// Turn string to path array
var pathArray = pathString
.replace(/[["']?([w]+)["']?]/g,".$1")
.split(".")
.splice(1);
// Add object prototype method
Object.prototype.path = function (path) {
try {
return [this].concat(path).reduce(function (f, l) {
return f[l];
});
} catch (e) {
console.error(e);
}
};
// usage
console.log(obj.path(pathArray));
console.log(obj.path([0,"doesNotExist"]));
answered Feb 23 '18 at 12:37
Oboo ChinOboo Chin
1,211818
1,211818
add a comment |
add a comment |
Working with Underscore
's property
or propertyOf
:
var test = {
foo: {
bar: {
baz: 'hello'
}
}
}
var string = 'foo.bar.baz';
// document.write(_.propertyOf(test)(string.split('.')))
document.write(_.property(string.split('.'))(test));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
Good Luck...
add a comment |
Working with Underscore
's property
or propertyOf
:
var test = {
foo: {
bar: {
baz: 'hello'
}
}
}
var string = 'foo.bar.baz';
// document.write(_.propertyOf(test)(string.split('.')))
document.write(_.property(string.split('.'))(test));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
Good Luck...
add a comment |
Working with Underscore
's property
or propertyOf
:
var test = {
foo: {
bar: {
baz: 'hello'
}
}
}
var string = 'foo.bar.baz';
// document.write(_.propertyOf(test)(string.split('.')))
document.write(_.property(string.split('.'))(test));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
Good Luck...
Working with Underscore
's property
or propertyOf
:
var test = {
foo: {
bar: {
baz: 'hello'
}
}
}
var string = 'foo.bar.baz';
// document.write(_.propertyOf(test)(string.split('.')))
document.write(_.property(string.split('.'))(test));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
Good Luck...
var test = {
foo: {
bar: {
baz: 'hello'
}
}
}
var string = 'foo.bar.baz';
// document.write(_.propertyOf(test)(string.split('.')))
document.write(_.property(string.split('.'))(test));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
var test = {
foo: {
bar: {
baz: 'hello'
}
}
}
var string = 'foo.bar.baz';
// document.write(_.propertyOf(test)(string.split('.')))
document.write(_.property(string.split('.'))(test));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
answered Jun 22 '18 at 11:49
AkashAkash
6,32013840
6,32013840
add a comment |
add a comment |
Inspired by @webjay's answer:
https://stackoverflow.com/a/46008856/4110122
I made this function which can you use it to Get/ Set/ Unset any value in object
function Object_Manager(obj, Path, value, Action)
{
try
{
if(Array.isArray(Path) == false)
{
Path = [Path];
}
let level = 0;
var Return_Value;
Path.reduce((a, b)=>{
level++;
if (level === Path.length)
{
if(Action === 'Set')
{
a[b] = value;
return value;
}
else if(Action === 'Get')
{
Return_Value = a[b];
}
else if(Action === 'Unset')
{
delete a[b];
}
}
else
{
return a[b];
}
}, obj);
return Return_Value;
}
catch(err)
{
console.error(err);
return obj;
}
}
To use it:
// Set
Object_Manager(Obj,[Level1,Level2,Level3],New_Value, 'Set');
// Get
Object_Manager(Obj,[Level1,Level2,Level3],'', 'Get');
// Unset
Object_Manager(Obj,[Level1,Level2,Level3],'', 'Unset');
add a comment |
Inspired by @webjay's answer:
https://stackoverflow.com/a/46008856/4110122
I made this function which can you use it to Get/ Set/ Unset any value in object
function Object_Manager(obj, Path, value, Action)
{
try
{
if(Array.isArray(Path) == false)
{
Path = [Path];
}
let level = 0;
var Return_Value;
Path.reduce((a, b)=>{
level++;
if (level === Path.length)
{
if(Action === 'Set')
{
a[b] = value;
return value;
}
else if(Action === 'Get')
{
Return_Value = a[b];
}
else if(Action === 'Unset')
{
delete a[b];
}
}
else
{
return a[b];
}
}, obj);
return Return_Value;
}
catch(err)
{
console.error(err);
return obj;
}
}
To use it:
// Set
Object_Manager(Obj,[Level1,Level2,Level3],New_Value, 'Set');
// Get
Object_Manager(Obj,[Level1,Level2,Level3],'', 'Get');
// Unset
Object_Manager(Obj,[Level1,Level2,Level3],'', 'Unset');
add a comment |
Inspired by @webjay's answer:
https://stackoverflow.com/a/46008856/4110122
I made this function which can you use it to Get/ Set/ Unset any value in object
function Object_Manager(obj, Path, value, Action)
{
try
{
if(Array.isArray(Path) == false)
{
Path = [Path];
}
let level = 0;
var Return_Value;
Path.reduce((a, b)=>{
level++;
if (level === Path.length)
{
if(Action === 'Set')
{
a[b] = value;
return value;
}
else if(Action === 'Get')
{
Return_Value = a[b];
}
else if(Action === 'Unset')
{
delete a[b];
}
}
else
{
return a[b];
}
}, obj);
return Return_Value;
}
catch(err)
{
console.error(err);
return obj;
}
}
To use it:
// Set
Object_Manager(Obj,[Level1,Level2,Level3],New_Value, 'Set');
// Get
Object_Manager(Obj,[Level1,Level2,Level3],'', 'Get');
// Unset
Object_Manager(Obj,[Level1,Level2,Level3],'', 'Unset');
Inspired by @webjay's answer:
https://stackoverflow.com/a/46008856/4110122
I made this function which can you use it to Get/ Set/ Unset any value in object
function Object_Manager(obj, Path, value, Action)
{
try
{
if(Array.isArray(Path) == false)
{
Path = [Path];
}
let level = 0;
var Return_Value;
Path.reduce((a, b)=>{
level++;
if (level === Path.length)
{
if(Action === 'Set')
{
a[b] = value;
return value;
}
else if(Action === 'Get')
{
Return_Value = a[b];
}
else if(Action === 'Unset')
{
delete a[b];
}
}
else
{
return a[b];
}
}, obj);
return Return_Value;
}
catch(err)
{
console.error(err);
return obj;
}
}
To use it:
// Set
Object_Manager(Obj,[Level1,Level2,Level3],New_Value, 'Set');
// Get
Object_Manager(Obj,[Level1,Level2,Level3],'', 'Get');
// Unset
Object_Manager(Obj,[Level1,Level2,Level3],'', 'Unset');
edited Nov 29 '18 at 8:15
answered Nov 28 '18 at 23:35
Mohamad HamoudayMohamad Hamouday
34748
34748
add a comment |
add a comment |
What about this solution:
setJsonValue: function (json, field, val) {
if (field !== undefined){
try {
eval("json." + field + " = val");
}
catch(e){
;
}
}
}
And this one, for getting:
getJsonValue: function (json, field){
var value = undefined;
if (field !== undefined) {
try {
eval("value = json." + field);
}
catch(e){
;
}
}
return value;
};
Probably some will consider them unsafe, but they must be much faster then, parsing the string.
add a comment |
What about this solution:
setJsonValue: function (json, field, val) {
if (field !== undefined){
try {
eval("json." + field + " = val");
}
catch(e){
;
}
}
}
And this one, for getting:
getJsonValue: function (json, field){
var value = undefined;
if (field !== undefined) {
try {
eval("value = json." + field);
}
catch(e){
;
}
}
return value;
};
Probably some will consider them unsafe, but they must be much faster then, parsing the string.
add a comment |
What about this solution:
setJsonValue: function (json, field, val) {
if (field !== undefined){
try {
eval("json." + field + " = val");
}
catch(e){
;
}
}
}
And this one, for getting:
getJsonValue: function (json, field){
var value = undefined;
if (field !== undefined) {
try {
eval("value = json." + field);
}
catch(e){
;
}
}
return value;
};
Probably some will consider them unsafe, but they must be much faster then, parsing the string.
What about this solution:
setJsonValue: function (json, field, val) {
if (field !== undefined){
try {
eval("json." + field + " = val");
}
catch(e){
;
}
}
}
And this one, for getting:
getJsonValue: function (json, field){
var value = undefined;
if (field !== undefined) {
try {
eval("value = json." + field);
}
catch(e){
;
}
}
return value;
};
Probably some will consider them unsafe, but they must be much faster then, parsing the string.
answered Dec 4 '13 at 19:54
Jonan GeorgievJonan Georgiev
461410
461410
add a comment |
add a comment |
Building off of Alnitak's answer:
if(!Object.prototype.byString){
//NEW byString which can update values
Object.prototype.byString = function(s, v, o) {
var _o = o || this;
s = s.replace(/[(w+)]/g, '.$1'); // CONVERT INDEXES TO PROPERTIES
s = s.replace(/^./, ''); // STRIP A LEADING DOT
var a = s.split('.'); //ARRAY OF STRINGS SPLIT BY '.'
for (var i = 0; i < a.length; ++i) {//LOOP OVER ARRAY OF STRINGS
var k = a[i];
if (k in _o) {//LOOP THROUGH OBJECT KEYS
if(_o.hasOwnProperty(k)){//USE ONLY KEYS WE CREATED
if(v !== undefined){//IF WE HAVE A NEW VALUE PARAM
if(i === a.length -1){//IF IT'S THE LAST IN THE ARRAY
_o[k] = v;
}
}
_o = _o[k];//NO NEW VALUE SO JUST RETURN THE CURRENT VALUE
}
} else {
return;
}
}
return _o;
};
}
This allows you to set a value as well!
I've created an npm package and github with this as well
add a comment |
Building off of Alnitak's answer:
if(!Object.prototype.byString){
//NEW byString which can update values
Object.prototype.byString = function(s, v, o) {
var _o = o || this;
s = s.replace(/[(w+)]/g, '.$1'); // CONVERT INDEXES TO PROPERTIES
s = s.replace(/^./, ''); // STRIP A LEADING DOT
var a = s.split('.'); //ARRAY OF STRINGS SPLIT BY '.'
for (var i = 0; i < a.length; ++i) {//LOOP OVER ARRAY OF STRINGS
var k = a[i];
if (k in _o) {//LOOP THROUGH OBJECT KEYS
if(_o.hasOwnProperty(k)){//USE ONLY KEYS WE CREATED
if(v !== undefined){//IF WE HAVE A NEW VALUE PARAM
if(i === a.length -1){//IF IT'S THE LAST IN THE ARRAY
_o[k] = v;
}
}
_o = _o[k];//NO NEW VALUE SO JUST RETURN THE CURRENT VALUE
}
} else {
return;
}
}
return _o;
};
}
This allows you to set a value as well!
I've created an npm package and github with this as well
add a comment |
Building off of Alnitak's answer:
if(!Object.prototype.byString){
//NEW byString which can update values
Object.prototype.byString = function(s, v, o) {
var _o = o || this;
s = s.replace(/[(w+)]/g, '.$1'); // CONVERT INDEXES TO PROPERTIES
s = s.replace(/^./, ''); // STRIP A LEADING DOT
var a = s.split('.'); //ARRAY OF STRINGS SPLIT BY '.'
for (var i = 0; i < a.length; ++i) {//LOOP OVER ARRAY OF STRINGS
var k = a[i];
if (k in _o) {//LOOP THROUGH OBJECT KEYS
if(_o.hasOwnProperty(k)){//USE ONLY KEYS WE CREATED
if(v !== undefined){//IF WE HAVE A NEW VALUE PARAM
if(i === a.length -1){//IF IT'S THE LAST IN THE ARRAY
_o[k] = v;
}
}
_o = _o[k];//NO NEW VALUE SO JUST RETURN THE CURRENT VALUE
}
} else {
return;
}
}
return _o;
};
}
This allows you to set a value as well!
I've created an npm package and github with this as well
Building off of Alnitak's answer:
if(!Object.prototype.byString){
//NEW byString which can update values
Object.prototype.byString = function(s, v, o) {
var _o = o || this;
s = s.replace(/[(w+)]/g, '.$1'); // CONVERT INDEXES TO PROPERTIES
s = s.replace(/^./, ''); // STRIP A LEADING DOT
var a = s.split('.'); //ARRAY OF STRINGS SPLIT BY '.'
for (var i = 0; i < a.length; ++i) {//LOOP OVER ARRAY OF STRINGS
var k = a[i];
if (k in _o) {//LOOP THROUGH OBJECT KEYS
if(_o.hasOwnProperty(k)){//USE ONLY KEYS WE CREATED
if(v !== undefined){//IF WE HAVE A NEW VALUE PARAM
if(i === a.length -1){//IF IT'S THE LAST IN THE ARRAY
_o[k] = v;
}
}
_o = _o[k];//NO NEW VALUE SO JUST RETURN THE CURRENT VALUE
}
} else {
return;
}
}
return _o;
};
}
This allows you to set a value as well!
I've created an npm package and github with this as well
edited Aug 15 '17 at 21:40
answered Aug 2 '17 at 19:16
TambTamb
16919
16919
add a comment |
add a comment |
protected by Samuel Liew♦ Oct 5 '15 at 9:21
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
Not sure what you are asking here? You want to be able to query part1.name and have the text "part1.name" returned? Or you want a means to get the value stored within part1.name?
– BonyT
Jun 27 '11 at 10:27
have you tried doing like
var part1name = someObject.part1name;
`– Rafay
Jun 27 '11 at 10:29
1
@BonyT : I want to query someObject.part1.name and return the value of it ("Part 1"). However, I want the query (I called it "the key") to be stored in a variable 'part1name'. Thanks for your reply. @3nigma : I have certainly do. But that is not my intention. Thanks for the reply.
– Komaruloh
Jun 27 '11 at 10:42
1
in the duplicate answer, i love fyr's answer stackoverflow.com/questions/8817394/…
– Steve Black
Mar 20 '13 at 2:09
1
See also Convert JavaScript string in dot notation into an object reference
– Bergi
Dec 15 '15 at 12:45