Access / process (nested) objects, arrays or JSON
I have a nested data structure containing objects and arrays. How can I extract the information, i.e. access a specific or multiple values (or keys)?
For example:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
How could I access the name
of the second item in items
?
javascript arrays object recursion data-manipulation
add a comment |
I have a nested data structure containing objects and arrays. How can I extract the information, i.e. access a specific or multiple values (or keys)?
For example:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
How could I access the name
of the second item in items
?
javascript arrays object recursion data-manipulation
2
At least you shouldn't talk about "a JSON" if you're not talking about the JSON interchange format. This is just an object in literal notation.
– Marcel Korpel
Mar 1 '13 at 13:09
17
@Marcel: It has to be read as "I have a data nested data structure or JSON, how can I access a specific value?". I know the difference, but many people don't and might be searching for "JSON" rather than "object". Many questions actually are of the form "how can I access X in this JSON". The only place where I mention JSON in my answer is where I explain what it is. If you have a suggestion how to communicate this in a better way, I'm all ears.
– Felix Kling
Mar 2 '13 at 0:46
possible duplicate of JSON find in JavaScript
– Travis J
Jun 12 '13 at 22:14
add a comment |
I have a nested data structure containing objects and arrays. How can I extract the information, i.e. access a specific or multiple values (or keys)?
For example:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
How could I access the name
of the second item in items
?
javascript arrays object recursion data-manipulation
I have a nested data structure containing objects and arrays. How can I extract the information, i.e. access a specific or multiple values (or keys)?
For example:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
How could I access the name
of the second item in items
?
javascript arrays object recursion data-manipulation
javascript arrays object recursion data-manipulation
edited May 24 at 22:22
AndrewL
7,61141641
7,61141641
asked Aug 12 '12 at 13:02
Felix Kling
543k125846902
543k125846902
2
At least you shouldn't talk about "a JSON" if you're not talking about the JSON interchange format. This is just an object in literal notation.
– Marcel Korpel
Mar 1 '13 at 13:09
17
@Marcel: It has to be read as "I have a data nested data structure or JSON, how can I access a specific value?". I know the difference, but many people don't and might be searching for "JSON" rather than "object". Many questions actually are of the form "how can I access X in this JSON". The only place where I mention JSON in my answer is where I explain what it is. If you have a suggestion how to communicate this in a better way, I'm all ears.
– Felix Kling
Mar 2 '13 at 0:46
possible duplicate of JSON find in JavaScript
– Travis J
Jun 12 '13 at 22:14
add a comment |
2
At least you shouldn't talk about "a JSON" if you're not talking about the JSON interchange format. This is just an object in literal notation.
– Marcel Korpel
Mar 1 '13 at 13:09
17
@Marcel: It has to be read as "I have a data nested data structure or JSON, how can I access a specific value?". I know the difference, but many people don't and might be searching for "JSON" rather than "object". Many questions actually are of the form "how can I access X in this JSON". The only place where I mention JSON in my answer is where I explain what it is. If you have a suggestion how to communicate this in a better way, I'm all ears.
– Felix Kling
Mar 2 '13 at 0:46
possible duplicate of JSON find in JavaScript
– Travis J
Jun 12 '13 at 22:14
2
2
At least you shouldn't talk about "a JSON" if you're not talking about the JSON interchange format. This is just an object in literal notation.
– Marcel Korpel
Mar 1 '13 at 13:09
At least you shouldn't talk about "a JSON" if you're not talking about the JSON interchange format. This is just an object in literal notation.
– Marcel Korpel
Mar 1 '13 at 13:09
17
17
@Marcel: It has to be read as "I have a data nested data structure or JSON, how can I access a specific value?". I know the difference, but many people don't and might be searching for "JSON" rather than "object". Many questions actually are of the form "how can I access X in this JSON". The only place where I mention JSON in my answer is where I explain what it is. If you have a suggestion how to communicate this in a better way, I'm all ears.
– Felix Kling
Mar 2 '13 at 0:46
@Marcel: It has to be read as "I have a data nested data structure or JSON, how can I access a specific value?". I know the difference, but many people don't and might be searching for "JSON" rather than "object". Many questions actually are of the form "how can I access X in this JSON". The only place where I mention JSON in my answer is where I explain what it is. If you have a suggestion how to communicate this in a better way, I'm all ears.
– Felix Kling
Mar 2 '13 at 0:46
possible duplicate of JSON find in JavaScript
– Travis J
Jun 12 '13 at 22:14
possible duplicate of JSON find in JavaScript
– Travis J
Jun 12 '13 at 22:14
add a comment |
20 Answers
20
active
oldest
votes
Preliminaries
JavaScript has only one data type which can contain multiple values: Object. An Array is a special form of object.
(Plain) Objects have the form
{key: value, key: value, ...}
Arrays have the form
[value, value, ...]
Both arrays and objects expose a key -> value
structure. Keys in an array must be numeric, whereas any string can be used as key in objects. The key-value pairs are also called the "properties".
Properties can be accessed either using dot notation
const value = obj.someProperty;
or bracket notation, if the property name would not be a valid JavaScript identifier name [spec], or the name is the value of a variable:
// the space is not a valid character in identifier names
const value = obj["some Property"];
// property name as variable
const name = "some Property";
const value = obj[name];
For that reason, array elements can only be accessed using bracket notation:
const value = arr[5]; // arr.5 would be a syntax error
// property name / index as variable
const x = 5;
const value = arr[x];
Wait... what about JSON?
JSON is a textual representation of data, just like XML, YAML, CSV, and others. To work with such data, it first has to be converted to JavaScript data types, i.e. arrays and objects (and how to work with those was just explained). How to parse JSON is explained in the question Parse JSON in JavaScript? .
Further reading material
How to access arrays and objects is fundamental JavaScript knowledge and therefore it is advisable to read the MDN JavaScript Guide, especially the sections
- Working with Objects
- Arrays
- Eloquent JavaScript - Data Structures
Accessing nested data structures
A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation.
Here is an example:
const data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
Let's assume we want to access the name
of the second item.
Here is how we can do it step-by-step:
As we can see data
is an object, hence we can access its properties using dot notation. The items
property is accessed as follows:
data.items
The value is an array, to access its second element, we have to use bracket notation:
data.items[1]
This value is an object and we use dot notation again to access the name
property. So we eventually get:
const item_name = data.items[1].name;
Alternatively, we could have used bracket notation for any of the properties, especially if the name contained characters that would have made it invalid for dot notation usage:
const item_name = data['items'][1]['name'];
I'm trying to access a property but I get only undefined
back?
Most of the time when you are getting undefined
, the object/array simply doesn't have a property with that name.
const foo = {bar: {baz: 42}};
console.log(foo.baz); // undefined
Use console.log
or console.dir
and inspect the structure of object / array. The property you are trying to access might be actually defined on a nested object / array.
console.log(foo.bar.baz); // 42
What if the property names are dynamic and I don't know them beforehand?
If the property names are unknown or we want to access all properties of an object / elements of an array, we can use the for...in
[MDN] loop for objects and the for
[MDN] loop for arrays to iterate over all properties / elements.
Objects
To iterate over all properties of data
, we can iterate over the object like so:
for (const prop in data) {
// `prop` contains the name of each property, i.e. `'code'` or `'items'`
// consequently, `data[prop]` refers to the value of each property, i.e.
// either `42` or the array
}
Depending on where the object comes from (and what you want to do), you might have to test in each iteration whether the property is really a property of the object, or it is an inherited property. You can do this with Object#hasOwnProperty
[MDN].
As alternative to for...in
with hasOwnProperty
, you can use Object.keys
[MDN] to get an array of property names:
Object.keys(data).forEach(function(prop) {
// `prop` is the property name
// `data[prop]` is the property value
});
Arrays
To iterate over all elements of the data.items
array, we use a for
loop:
for(let i = 0, l = data.items.length; i < l; i++) {
// `i` will take on the values `0`, `1`, `2`,..., i.e. in each iteration
// we can access the next element in the array with `data.items[i]`, example:
//
// var obj = data.items[i];
//
// Since each element is an object (in our example),
// we can now access the objects properties with `obj.id` and `obj.name`.
// We could also use `data.items[i].id`.
}
One could also use for...in
to iterate over arrays, but there are reasons why this should be avoided: Why is 'for(var item in list)' with arrays considered bad practice in JavaScript?.
With the increasing browser support of ECMAScript 5, the array method forEach
[MDN] becomes an interesting alternative as well:
data.items.forEach(function(value, index, array) {
// The callback is executed for each element in the array.
// `value` is the element itself (equivalent to `array[index]`)
// `index` will be the index of the element in the array
// `array` is a reference to the array itself (i.e. `data.items` in this case)
});
In environments supporting ES2015 (ES6), you can also use the for...of
[MDN] loop, which not only works for arrays, but for any iterable:
for (const item of data.items) {
// `item` is the array element, **not** the index
}
In each iteration, for...of
directly gives us the next element of the iterable, there is no "index" to access or use.
What if the "depth" of the data structure is unknown to me?
In addition to unknown keys, the "depth" of the data structure (i.e. how many nested objects) it has, might be unknown as well. How to access deeply nested properties usually depends on the exact data structure.
But if the data structure contains repeating patterns, e.g. the representation of a binary tree, the solution typically includes to recursively [Wikipedia] access each level of the data structure.
Here is an example to get the first leaf node of a binary tree:
function getLeaf(node) {
if (node.leftChild) {
return getLeaf(node.leftChild); // <- recursive call
}
else if (node.rightChild) {
return getLeaf(node.rightChild); // <- recursive call
}
else { // node must be a leaf node
return node;
}
}
const first_leaf = getLeaf(root);
const root = {
leftChild: {
leftChild: {
leftChild: null,
rightChild: null,
data: 42
},
rightChild: {
leftChild: null,
rightChild: null,
data: 5
}
},
rightChild: {
leftChild: {
leftChild: null,
rightChild: null,
data: 6
},
rightChild: {
leftChild: null,
rightChild: null,
data: 7
}
}
};
function getLeaf(node) {
if (node.leftChild) {
return getLeaf(node.leftChild);
} else if (node.rightChild) {
return getLeaf(node.rightChild);
} else { // node must be a leaf node
return node;
}
}
console.log(getLeaf(root).data);
A more generic way to access a nested data structure with unknown keys and depth is to test the type of the value and act accordingly.
Here is an example which adds all primitive values inside a nested data structure into an array (assuming it does not contain any functions). If we encounter an object (or array) we simply call toArray
again on that value (recursive call).
function toArray(obj) {
const result = ;
for (const prop in obj) {
const value = obj[prop];
if (typeof value === 'object') {
result.push(toArray(value)); // <- recursive call
}
else {
result.push(value);
}
}
return result;
}
const data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
function toArray(obj) {
const result = ;
for (const prop in obj) {
const value = obj[prop];
if (typeof value === 'object') {
result.push(toArray(value));
} else {
result.push(value);
}
}
return result;
}
console.log(toArray(data));
Helpers
Since the structure of a complex object or array is not necessarily obvious, we can inspect the value at each step to decide how to move further. console.log
[MDN] and console.dir
[MDN] help us doing this. For example (output of the Chrome console):
> console.log(data.items)
[ Object, Object ]
Here we see that that data.items
is an array with two elements which are both objects. In Chrome console the objects can even be expanded and inspected immediately.
> console.log(data.items[1])
Object
id: 2
name: "bar"
__proto__: Object
This tells us that data.items[1]
is an object, and after expanding it we see that it has three properties, id
, name
and __proto__
. The latter is an internal property used for the prototype chain of the object. The prototype chain and inheritance is out of scope for this answer, though.
3
Some of what's being linked here is really asking how to do this in jQuery, which to be fair does simplify 1 or 2 things here. Not sure whether to make this more of a megapost or answer those separately - the basics covered here on what's an object what's an array are usually what's really being asked... .
– Chris Moschini
Apr 2 '13 at 9:29
@felix-kling One thing... with nested objects, such aslet object = {a: 1, b: 2, c: { a: 3, b: 4 }};
, this returns an array containing an array for each nested object, in this case[ 1, 2, [ 3, 4 ] ]
Wouldn't it be better to to use concat in the recursive call instead of push ? (requiring result to be mutable)
– ElFitz
May 3 at 15:44
This is the most in-depth answer I have ever seen on Stack Overflow - and it answered my question! Thanks!
– William Jones
Nov 15 at 19:58
add a comment |
You can access it this way
data.items[1].name
or
data["items"][1]["name"]
Both ways are equal.
Yea but you can't do data["items"].1.name
– neaumusic
Oct 21 '15 at 19:01
1
First is far more intuitive, readable and shorter ;) I prefer using bracket property syntax only when the property name is variable.
– DanteTheSmith
Oct 2 '17 at 11:59
add a comment |
In case you're trying to access an item
from the example structure by id
or name
, without knowing it's position in the array, the easiest way to do it would be to use underscore.js library:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
_.find(data.items, function(item) {
return item.id === 2;
});
// Object {id: 2, name: "bar"}
From my experience, using higher order functions instead of for
or for..in
loops results in code that is easier to reason about, and hence more maintainable.
Just my 2 cents.
add a comment |
At times, accessing a nested object using a string can be desirable. The simple approach is the first level, for example
var obj = { hello: "world" };
var key = "hello";
alert(obj[key]);//world
But this is often not the case with complex json. As json becomes more complex, the approaches for finding values inside of the json also become complex. A recursive approach for navigating the json is best, and how that recursion is leveraged will depend on the type of data being searched for. If there are conditional statements involved, a json search can be a good tool to use.
If the property being accessed is already known, but the path is complex, for example in this object
var obj = {
arr: [
{ id: 1, name: "larry" },
{ id: 2, name: "curly" },
{ id: 3, name: "moe" }
]
};
And you know you want to get the first result of the array in the object, perhaps you would like to use
var moe = obj["arr[0].name"];
However, that will cause an exception as there is no property of object with that name. The solution to be able to use this would be to flatten the tree aspect of the object. This can be done recursively.
function flatten(obj){
var root = {};
(function tree(obj, index){
var suffix = toString.call(obj) == "[object Array]" ? "]" : "";
for(var key in obj){
if(!obj.hasOwnProperty(key))continue;
root[index+key+suffix] = obj[key];
if( toString.call(obj[key]) == "[object Array]" )tree(obj[key],index+key+suffix+"[");
if( toString.call(obj[key]) == "[object Object]" )tree(obj[key],index+key+suffix+".");
}
})(obj,"");
return root;
}
Now, the complex object can be flattened
var obj = previous definition;
var flat = flatten(obj);
var moe = flat["arr[0].name"];//moe
Here is a jsFiddle Demo
of this approach being used.
WTH would you want to useobj["arr[0].name"]
instead ofobj.arr[0].name
? You hardly need/want to deal with flattened objects except for serialisation.
– Bergi
Aug 19 '14 at 16:00
@Bergi - I see this question commonly, and since this is being used canonically, I posted an answer to that version of it. If it is avoidable it is much faster to use obj.arr[0].name, but sometimes people want to pass string accessors around and this is an example of doing that.
– Travis J
Aug 19 '14 at 17:28
Urgh. Still, there's hardly a reason to flatten the complete object only to use a single string path, you could simply parse that and do a dynamic lookup.
– Bergi
Aug 19 '14 at 17:29
add a comment |
Objects and arrays has a lot of built-in methods that can help you with processing data.
Note: in many of the examples I'm using arrow functions. They are similar to function expressions, but they bind the this
value lexically.
Object.keys()
, Object.values()
(ES 2017) and Object.entries()
(ES 2017)
Object.keys()
returns an array of object's keys, Object.values()
returns an array of object's values, and Object.entries()
returns an array of object's keys and corresponding values in a format [key, value]
.
const obj = {
a: 1
,b: 2
,c: 3
}
console.log(Object.keys(obj)) // ['a', 'b', 'c']
console.log(Object.values(obj)) // [1, 2, 3]
console.log(Object.entries(obj)) // [['a', 1], ['b', 2], ['c', 3]]
Object.entries()
with a for-of loop and destructuring assignment
const obj = {
a: 1
,b: 2
,c: 3
}
for (const [key, value] of Object.entries(obj)) {
console.log(`key: ${key}, value: ${value}`)
}
It's very convenient to iterate the result of Object.entries()
with a for-of loop and destructuring assignment.
For-of loop lets you iterate array elements. The syntax is for (const element of array)
(we can replace const
with var
or let
, but it's better to use const
if we don't intend to modify element
).
Destructuring assignment lets you extract values from an array or an object and assign them to variables. In this case const [key, value]
means that instead of assigning the [key, value]
array to element
, we assign the first element of that array to key
and the second element to value
. It is equivalent to this:
for (const element of Object.entries(obj)) {
const key = element[0]
,value = element[1]
}
As you can see, destructuring makes this a lot simpler.
Array.prototype.every()
and Array.prototype.some()
The every()
method returns true
if the specified callback function returns true
for every element of the array. The some()
method returns true
if the specified callback function returns true
for some (at least one) element.
const arr = [1, 2, 3]
// true, because every element is greater than 0
console.log(arr.every(x => x > 0))
// false, because 3^2 is greater than 5
console.log(arr.every(x => Math.pow(x, 2) < 5))
// true, because 2 is even (the remainder from dividing by 2 is 0)
console.log(arr.some(x => x % 2 === 0))
// false, because none of the elements is equal to 5
console.log(arr.some(x => x === 5))
Array.prototype.find()
and Array.prototype.filter()
The find()
methods returns the first element which satisfies the provided callback function. The filter()
method returns an array of all elements which satisfies the provided callback function.
const arr = [1, 2, 3]
// 2, because 2^2 !== 2
console.log(arr.find(x => x !== Math.pow(x, 2)))
// 1, because it's the first element
console.log(arr.find(x => true))
// undefined, because none of the elements equals 7
console.log(arr.find(x => x === 7))
// [2, 3], because these elements are greater than 1
console.log(arr.filter(x => x > 1))
// [1, 2, 3], because the function returns true for all elements
console.log(arr.filter(x => true))
// , because none of the elements equals neither 6 nor 7
console.log(arr.filter(x => x === 6 || x === 7))
Array.prototype.map()
The map()
method returns an array with the results of calling a provided callback function on the array elements.
const arr = [1, 2, 3]
console.log(arr.map(x => x + 1)) // [2, 3, 4]
console.log(arr.map(x => String.fromCharCode(96 + x))) // ['a', 'b', 'c']
console.log(arr.map(x => x)) // [1, 2, 3] (no-op)
console.log(arr.map(x => Math.pow(x, 2))) // [1, 4, 9]
console.log(arr.map(String)) // ['1', '2', '3']
Array.prototype.reduce()
The reduce()
method reduces an array to a single value by calling the provided callback function with two elements.
const arr = [1, 2, 3]
// Sum of array elements.
console.log(arr.reduce((a, b) => a + b)) // 6
// The largest number in the array.
console.log(arr.reduce((a, b) => a > b ? a : b)) // 3
The reduce()
method takes an optional second parameter, which is the initial value. This is useful when the array on which you call reduce()
can has zero or one elements. For example, if we wanted to create a function sum()
which takes an array as an argument and returns the sum of all elements, we could write it like that:
const sum = arr => arr.reduce((a, b) => a + b, 0)
console.log(sum()) // 0
console.log(sum([4])) // 4
console.log(sum([2, 5])) // 7
add a comment |
This question is quite old, so as a contemporary update. With the onset of ES2015 there are alternatives to get a hold of the data you require. There is now a feature called object destructuring for accessing nested objects.
const data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
const {
items: [, {
name: secondName
}]
} = data;
console.log(secondName);
The above example creates a variable called secondName
from the name
key from an array called items
, the lonely ,
says skip the first object in the array.
Notably it's probably overkill for this example, as simple array acccess is easier to read, but it comes in useful when breaking apart objects in general.
This is very brief intro to your specific use case, destructuring can be an unusual syntax to get used to at first. I'd recommend reading Mozilla's Destructuring Assignment documentation to learn more.
add a comment |
Using JSONPath would be one of the most flexible solutions if you are willing to include a library:
https://github.com/s3u/JSONPath (node and browser)
For your use case the json path would be:
$..items[1].name
so:
var secondName = jsonPath.eval(data, "$..items[1].name");
Using eval() is not good solution. Instead first class function can be used.
– pradeep gowda
Sep 27 '17 at 12:18
add a comment |
I prefer JQuery. It's cleaner and easy to read.
$.each($.parseJSON(data), function (key, value) {
alert(value.<propertyname>);
});
add a comment |
You could use lodash _get
function:
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.get(object, 'a[0].b.c');
// => 3
add a comment |
To access a nested attribute, you need to specify its name and then search through the object.
If you already know the exact path, then you can hardcode it in your script like so:
data['items'][1]['name']
these also work -
data.items[1].name
data['items'][1].name
data.items[1]['name']
When you don't know the exact name before hand, or a user is the one who provides the name for you. Then dynamically searching through the data structure is required. Some suggested here that the search can be done using a for
loop, but there is a very simple way to traverse a path using Array.reduce
.
const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] }
const path = [ 'items', '1', 'name']
let result = path.reduce((a,v) => a[v], data)
The path is a way to say: First take the object with key items
, which happens to be an array. Then take the 1
-st element (0 index arrays). Last take the object with key name
in that array element, which happens to be the string bar
.
If you have a very long path, you might even use String.split
to make all of this easier -
'items.1.name'.split('.').reduce((a,v) => a[v], data)
This is just plain JavaScript, without using any third party libraries like jQuery or lodash.
add a comment |
If you are looking for one or more objects that meets certain criteria you have a few options using query-js
//will return all elements with an id larger than 1
data.items.where(function(e){return e.id > 1;});
//will return the first element with an id larger than 1
data.items.first(function(e){return e.id > 1;});
//will return the first element with an id larger than 1
//or the second argument if non are found
data.items.first(function(e){return e.id > 1;},{id:-1,name:""});
There's also a single
and a singleOrDefault
they work much like first
and firstOrDefault
respectively. The only difference is that they will throw if more than one match is found.
for further explanation of query-js you can start with this post
I would love to know how this could be improved. Care to leave a comment?
– Rune FS
Jun 18 '15 at 18:42
add a comment |
The Underscore js Way
Which is a JavaScript library that provides a whole mess of useful functional programming
helpers without extending any built-in objects.
Solution:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
var item = _.findWhere(data.items, {
id: 2
});
if (!_.isUndefined(item)) {
console.log('NAME =>', item.name);
}
//using find -
var item = _.find(data.items, function(item) {
return item.id === 2;
});
if (!_.isUndefined(item)) {
console.log('NAME =>', item.name);
}
add a comment |
Accessing dynamically multi levels object.
var obj = {
name: "salut",
subobj: {
subsubobj: {
names: "I am sub sub obj"
}
}
};
var level = "subobj.subsubobj.names";
level = level.split(".");
var currentObjState = obj;
for (var i = 0; i < level.length; i++) {
currentObjState = currentObjState[level[i]];
}
console.log(currentObjState);
Working fiddle: https://jsfiddle.net/andreitodorut/3mws3kjL/
add a comment |
I don't think questioner just only concern one level nested object, so I present the following demo to demonstrate how to access the node of deeply nested json object. All right, let's find the node with id '5'.
var data = {
code: 42,
items: [{
id: 1,
name: 'aaa',
items: [{
id: 3,
name: 'ccc'
}, {
id: 4,
name: 'ddd'
}]
}, {
id: 2,
name: 'bbb',
items: [{
id: 5,
name: 'eee'
}, {
id: 6,
name: 'fff'
}]
}]
};
var jsonloop = new JSONLoop(data, 'id', 'items');
jsonloop.findNodeById(data, 5, function(err, node) {
if (err) {
document.write(err);
} else {
document.write(JSON.stringify(node, null, 2));
}
});
<script src="https://rawgit.com/dabeng/JSON-Loop/master/JSONLoop.js"></script>
How do I access nested json object using variables. data = {a: {b:'ss'}}; var key = a.b data[key] not working
– Pasupathi Rajamanickam
Nov 14 '17 at 20:51
add a comment |
Old question but as nobody mentioned lodash (just underscore).
In case you are already using lodash in your project, I think an elegant way to do this in a complex example:
Opt 1
_.get(response, ['output', 'fund', 'data', '0', 'children', '0', 'group', 'myValue'], '')
same as:
Opt 2
response.output.fund.data[0].children[0].group.myValue
The difference between the first and second option is that in the Opt 1 if you have one of the properties missing (undefined) in the path you don't get an error, it returns you the third parameter.
For array filter lodash has _.find()
but I'd rather use the regular filter()
. But I still think the above method _.get()
is super useful when working with really complex data. I faced in the past really complex APIs and it was handy!
I hope it can be useful for who's looking for options to manipulate really complex data which the title implies.
add a comment |
var ourStorage = {
"desk": {
"drawer": "stapler"
},
"cabinet": {
"top drawer": {
"folder1": "a file",
"folder2": "secrets"
},
"bottom drawer": "soda"
}
};
ourStorage.cabinet["top drawer"].folder2; // Outputs -> "secrets"
or
//parent.subParent.subsubParent["almost there"]["final property"]
Basically, use a dot between each descendant that unfolds underneath it and when you have object names made out of two strings, you must use the ["obj Name"] notation. Otherwise, just a dot would suffice;
Source: https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-objects
to add to this, accessing nested Arrays would happen like so:
var ourPets = [
{
animalType: "cat",
names: [
"Meowzer",
"Fluffy",
"Kit-Cat"
]
},
{
animalType: "dog",
names: [
"Spot",
"Bowser",
"Frankie"
]
}
];
ourPets[0].names[1]; // Outputs "Fluffy"
ourPets[1].names[0]; // Outputs "Spot"
Source: https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-arrays/
While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review
– Robert
Aug 19 at 23:33
I edited the post. Allthough people were quick to give bad rep to it. Next time I'll refrain from giving an answer.
– Riddick
Aug 20 at 0:04
@Riddick don't refrain, just make sure you don't post only a link
– reggaeguitar
Sep 27 at 18:02
add a comment |
A pythonic, recursive and functional approach to unravel arbitrary JSON trees:
handlers = {
list: iterate,
dict: delve,
str: emit_li,
float: emit_li,
}
def emit_li(stuff, strong=False):
emission = '<li><strong>%s</strong></li>' if strong else '<li>%s</li>'
print(emission % stuff)
def iterate(a_list):
print('<ul>')
map(unravel, a_list)
print('</ul>')
def delve(a_dict):
print('<ul>')
for key, value in a_dict.items():
emit_li(key, strong=True)
unravel(value)
print('</ul>')
def unravel(structure):
h = handlers[type(structure)]
return h(structure)
unravel(data)
where data is a python list (parsed from a JSON text string):
data = [
{'data': {'customKey1': 'customValue1',
'customKey2': {'customSubKey1': {'customSubSubKey1': 'keyvalue'}}},
'geometry': {'location': {'lat': 37.3860517, 'lng': -122.0838511},
'viewport': {'northeast': {'lat': 37.4508789,
'lng': -122.0446721},
'southwest': {'lat': 37.3567599,
'lng': -122.1178619}}},
'name': 'Mountain View',
'scope': 'GOOGLE',
'types': ['locality', 'political']}
]
2
This question is about JavaScript, not Python. Not sure whether there is an equivalent question for Python.
– Felix Kling
Dec 28 '16 at 19:54
Lo, thanks for your Python answer on JavaScript Question
– Ilyas karim
Mar 27 at 19:46
Tough crowd, here.
– pX0r
Jul 19 at 7:05
add a comment |
jQuery's grep function lets you filter through an array:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
$.grep(data.items, function(item) {
if (item.id === 2) {
console.log(item.id); //console id of item
console.log(item.name); //console name of item
console.log(item); //console item object
return item; //returns item object
}
});
// Object {id: 2, name: "bar"}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
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
1. Oliver Steele's nested object access pattern
The easiest and the cleanest way is to use Oliver Steele's nested object access pattern
const name = ((user || {}).personalInfo || {}).name;
With this notation, you'll never run into
Cannot read property 'name' of undefined.
You basically check if user exists, if not, you create an empty object on the fly. This way, the next level key will always be accessed from an object that exists or an empty object, but never from undefined.
2. Access Nested Objects Using Array Reduce
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', 'addresses', 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.
This question is primarily about access properties that exist. There is already a question about what you are referring to (and already including most of your solutions): Access Javascript nested objects safely or Accessing nested JavaScript objects with string key. But anyway: "Unfortunately, you cannot access nested arrays with this trick." Why not? Arrays are objects, so it should work just as well. Can you provide an example where it does not?
– Felix Kling
Jul 7 at 15:47
@FelixKling When we try to access arrays with Oliver Steele pattern, we won't be able to create array on 'n' length on the fly and access nth index without getting 'undefined' error. Ex.((user || {}).address || new Array(3))[1].name
– Dinesh Pandiyan
Jul 8 at 16:20
1
You are not applying your pattern consistently. Of course...[1].bar
would result in an error if the element1
didn't exist. But that's also the case for....foo.bar
iffoo
didn't exist. You have to "guard" accessing1
as well, just like you "guard" any other property access. An array is just an object. An "array element" is just a property. Correctly applied it would be(((user || {}).address || {})[1] || {}).name
.
– Felix Kling
Jul 9 at 3:49
This is great. It didn't strike me this way. Thank @FelixKling, I'll go update the blog posts.
– Dinesh Pandiyan
Jul 9 at 4:01
@DineshPandiyan you should disclose that you're the author of typy, I just came here after reading your blog post
– reggaeguitar
Sep 27 at 18:03
add a comment |
Using lodash would be good solution
Ex:
var object = { 'a': { 'b': { 'c': 3 } } };
_.get(object, 'a.b.c');
// => 3
How is this different from Access / process (nested) objects, arrays or JSON?
– Heretic Monkey
Feb 17 at 23:52
add a comment |
protected by Samuel Liew♦ Oct 5 '15 at 8:58
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?
20 Answers
20
active
oldest
votes
20 Answers
20
active
oldest
votes
active
oldest
votes
active
oldest
votes
Preliminaries
JavaScript has only one data type which can contain multiple values: Object. An Array is a special form of object.
(Plain) Objects have the form
{key: value, key: value, ...}
Arrays have the form
[value, value, ...]
Both arrays and objects expose a key -> value
structure. Keys in an array must be numeric, whereas any string can be used as key in objects. The key-value pairs are also called the "properties".
Properties can be accessed either using dot notation
const value = obj.someProperty;
or bracket notation, if the property name would not be a valid JavaScript identifier name [spec], or the name is the value of a variable:
// the space is not a valid character in identifier names
const value = obj["some Property"];
// property name as variable
const name = "some Property";
const value = obj[name];
For that reason, array elements can only be accessed using bracket notation:
const value = arr[5]; // arr.5 would be a syntax error
// property name / index as variable
const x = 5;
const value = arr[x];
Wait... what about JSON?
JSON is a textual representation of data, just like XML, YAML, CSV, and others. To work with such data, it first has to be converted to JavaScript data types, i.e. arrays and objects (and how to work with those was just explained). How to parse JSON is explained in the question Parse JSON in JavaScript? .
Further reading material
How to access arrays and objects is fundamental JavaScript knowledge and therefore it is advisable to read the MDN JavaScript Guide, especially the sections
- Working with Objects
- Arrays
- Eloquent JavaScript - Data Structures
Accessing nested data structures
A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation.
Here is an example:
const data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
Let's assume we want to access the name
of the second item.
Here is how we can do it step-by-step:
As we can see data
is an object, hence we can access its properties using dot notation. The items
property is accessed as follows:
data.items
The value is an array, to access its second element, we have to use bracket notation:
data.items[1]
This value is an object and we use dot notation again to access the name
property. So we eventually get:
const item_name = data.items[1].name;
Alternatively, we could have used bracket notation for any of the properties, especially if the name contained characters that would have made it invalid for dot notation usage:
const item_name = data['items'][1]['name'];
I'm trying to access a property but I get only undefined
back?
Most of the time when you are getting undefined
, the object/array simply doesn't have a property with that name.
const foo = {bar: {baz: 42}};
console.log(foo.baz); // undefined
Use console.log
or console.dir
and inspect the structure of object / array. The property you are trying to access might be actually defined on a nested object / array.
console.log(foo.bar.baz); // 42
What if the property names are dynamic and I don't know them beforehand?
If the property names are unknown or we want to access all properties of an object / elements of an array, we can use the for...in
[MDN] loop for objects and the for
[MDN] loop for arrays to iterate over all properties / elements.
Objects
To iterate over all properties of data
, we can iterate over the object like so:
for (const prop in data) {
// `prop` contains the name of each property, i.e. `'code'` or `'items'`
// consequently, `data[prop]` refers to the value of each property, i.e.
// either `42` or the array
}
Depending on where the object comes from (and what you want to do), you might have to test in each iteration whether the property is really a property of the object, or it is an inherited property. You can do this with Object#hasOwnProperty
[MDN].
As alternative to for...in
with hasOwnProperty
, you can use Object.keys
[MDN] to get an array of property names:
Object.keys(data).forEach(function(prop) {
// `prop` is the property name
// `data[prop]` is the property value
});
Arrays
To iterate over all elements of the data.items
array, we use a for
loop:
for(let i = 0, l = data.items.length; i < l; i++) {
// `i` will take on the values `0`, `1`, `2`,..., i.e. in each iteration
// we can access the next element in the array with `data.items[i]`, example:
//
// var obj = data.items[i];
//
// Since each element is an object (in our example),
// we can now access the objects properties with `obj.id` and `obj.name`.
// We could also use `data.items[i].id`.
}
One could also use for...in
to iterate over arrays, but there are reasons why this should be avoided: Why is 'for(var item in list)' with arrays considered bad practice in JavaScript?.
With the increasing browser support of ECMAScript 5, the array method forEach
[MDN] becomes an interesting alternative as well:
data.items.forEach(function(value, index, array) {
// The callback is executed for each element in the array.
// `value` is the element itself (equivalent to `array[index]`)
// `index` will be the index of the element in the array
// `array` is a reference to the array itself (i.e. `data.items` in this case)
});
In environments supporting ES2015 (ES6), you can also use the for...of
[MDN] loop, which not only works for arrays, but for any iterable:
for (const item of data.items) {
// `item` is the array element, **not** the index
}
In each iteration, for...of
directly gives us the next element of the iterable, there is no "index" to access or use.
What if the "depth" of the data structure is unknown to me?
In addition to unknown keys, the "depth" of the data structure (i.e. how many nested objects) it has, might be unknown as well. How to access deeply nested properties usually depends on the exact data structure.
But if the data structure contains repeating patterns, e.g. the representation of a binary tree, the solution typically includes to recursively [Wikipedia] access each level of the data structure.
Here is an example to get the first leaf node of a binary tree:
function getLeaf(node) {
if (node.leftChild) {
return getLeaf(node.leftChild); // <- recursive call
}
else if (node.rightChild) {
return getLeaf(node.rightChild); // <- recursive call
}
else { // node must be a leaf node
return node;
}
}
const first_leaf = getLeaf(root);
const root = {
leftChild: {
leftChild: {
leftChild: null,
rightChild: null,
data: 42
},
rightChild: {
leftChild: null,
rightChild: null,
data: 5
}
},
rightChild: {
leftChild: {
leftChild: null,
rightChild: null,
data: 6
},
rightChild: {
leftChild: null,
rightChild: null,
data: 7
}
}
};
function getLeaf(node) {
if (node.leftChild) {
return getLeaf(node.leftChild);
} else if (node.rightChild) {
return getLeaf(node.rightChild);
} else { // node must be a leaf node
return node;
}
}
console.log(getLeaf(root).data);
A more generic way to access a nested data structure with unknown keys and depth is to test the type of the value and act accordingly.
Here is an example which adds all primitive values inside a nested data structure into an array (assuming it does not contain any functions). If we encounter an object (or array) we simply call toArray
again on that value (recursive call).
function toArray(obj) {
const result = ;
for (const prop in obj) {
const value = obj[prop];
if (typeof value === 'object') {
result.push(toArray(value)); // <- recursive call
}
else {
result.push(value);
}
}
return result;
}
const data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
function toArray(obj) {
const result = ;
for (const prop in obj) {
const value = obj[prop];
if (typeof value === 'object') {
result.push(toArray(value));
} else {
result.push(value);
}
}
return result;
}
console.log(toArray(data));
Helpers
Since the structure of a complex object or array is not necessarily obvious, we can inspect the value at each step to decide how to move further. console.log
[MDN] and console.dir
[MDN] help us doing this. For example (output of the Chrome console):
> console.log(data.items)
[ Object, Object ]
Here we see that that data.items
is an array with two elements which are both objects. In Chrome console the objects can even be expanded and inspected immediately.
> console.log(data.items[1])
Object
id: 2
name: "bar"
__proto__: Object
This tells us that data.items[1]
is an object, and after expanding it we see that it has three properties, id
, name
and __proto__
. The latter is an internal property used for the prototype chain of the object. The prototype chain and inheritance is out of scope for this answer, though.
3
Some of what's being linked here is really asking how to do this in jQuery, which to be fair does simplify 1 or 2 things here. Not sure whether to make this more of a megapost or answer those separately - the basics covered here on what's an object what's an array are usually what's really being asked... .
– Chris Moschini
Apr 2 '13 at 9:29
@felix-kling One thing... with nested objects, such aslet object = {a: 1, b: 2, c: { a: 3, b: 4 }};
, this returns an array containing an array for each nested object, in this case[ 1, 2, [ 3, 4 ] ]
Wouldn't it be better to to use concat in the recursive call instead of push ? (requiring result to be mutable)
– ElFitz
May 3 at 15:44
This is the most in-depth answer I have ever seen on Stack Overflow - and it answered my question! Thanks!
– William Jones
Nov 15 at 19:58
add a comment |
Preliminaries
JavaScript has only one data type which can contain multiple values: Object. An Array is a special form of object.
(Plain) Objects have the form
{key: value, key: value, ...}
Arrays have the form
[value, value, ...]
Both arrays and objects expose a key -> value
structure. Keys in an array must be numeric, whereas any string can be used as key in objects. The key-value pairs are also called the "properties".
Properties can be accessed either using dot notation
const value = obj.someProperty;
or bracket notation, if the property name would not be a valid JavaScript identifier name [spec], or the name is the value of a variable:
// the space is not a valid character in identifier names
const value = obj["some Property"];
// property name as variable
const name = "some Property";
const value = obj[name];
For that reason, array elements can only be accessed using bracket notation:
const value = arr[5]; // arr.5 would be a syntax error
// property name / index as variable
const x = 5;
const value = arr[x];
Wait... what about JSON?
JSON is a textual representation of data, just like XML, YAML, CSV, and others. To work with such data, it first has to be converted to JavaScript data types, i.e. arrays and objects (and how to work with those was just explained). How to parse JSON is explained in the question Parse JSON in JavaScript? .
Further reading material
How to access arrays and objects is fundamental JavaScript knowledge and therefore it is advisable to read the MDN JavaScript Guide, especially the sections
- Working with Objects
- Arrays
- Eloquent JavaScript - Data Structures
Accessing nested data structures
A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation.
Here is an example:
const data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
Let's assume we want to access the name
of the second item.
Here is how we can do it step-by-step:
As we can see data
is an object, hence we can access its properties using dot notation. The items
property is accessed as follows:
data.items
The value is an array, to access its second element, we have to use bracket notation:
data.items[1]
This value is an object and we use dot notation again to access the name
property. So we eventually get:
const item_name = data.items[1].name;
Alternatively, we could have used bracket notation for any of the properties, especially if the name contained characters that would have made it invalid for dot notation usage:
const item_name = data['items'][1]['name'];
I'm trying to access a property but I get only undefined
back?
Most of the time when you are getting undefined
, the object/array simply doesn't have a property with that name.
const foo = {bar: {baz: 42}};
console.log(foo.baz); // undefined
Use console.log
or console.dir
and inspect the structure of object / array. The property you are trying to access might be actually defined on a nested object / array.
console.log(foo.bar.baz); // 42
What if the property names are dynamic and I don't know them beforehand?
If the property names are unknown or we want to access all properties of an object / elements of an array, we can use the for...in
[MDN] loop for objects and the for
[MDN] loop for arrays to iterate over all properties / elements.
Objects
To iterate over all properties of data
, we can iterate over the object like so:
for (const prop in data) {
// `prop` contains the name of each property, i.e. `'code'` or `'items'`
// consequently, `data[prop]` refers to the value of each property, i.e.
// either `42` or the array
}
Depending on where the object comes from (and what you want to do), you might have to test in each iteration whether the property is really a property of the object, or it is an inherited property. You can do this with Object#hasOwnProperty
[MDN].
As alternative to for...in
with hasOwnProperty
, you can use Object.keys
[MDN] to get an array of property names:
Object.keys(data).forEach(function(prop) {
// `prop` is the property name
// `data[prop]` is the property value
});
Arrays
To iterate over all elements of the data.items
array, we use a for
loop:
for(let i = 0, l = data.items.length; i < l; i++) {
// `i` will take on the values `0`, `1`, `2`,..., i.e. in each iteration
// we can access the next element in the array with `data.items[i]`, example:
//
// var obj = data.items[i];
//
// Since each element is an object (in our example),
// we can now access the objects properties with `obj.id` and `obj.name`.
// We could also use `data.items[i].id`.
}
One could also use for...in
to iterate over arrays, but there are reasons why this should be avoided: Why is 'for(var item in list)' with arrays considered bad practice in JavaScript?.
With the increasing browser support of ECMAScript 5, the array method forEach
[MDN] becomes an interesting alternative as well:
data.items.forEach(function(value, index, array) {
// The callback is executed for each element in the array.
// `value` is the element itself (equivalent to `array[index]`)
// `index` will be the index of the element in the array
// `array` is a reference to the array itself (i.e. `data.items` in this case)
});
In environments supporting ES2015 (ES6), you can also use the for...of
[MDN] loop, which not only works for arrays, but for any iterable:
for (const item of data.items) {
// `item` is the array element, **not** the index
}
In each iteration, for...of
directly gives us the next element of the iterable, there is no "index" to access or use.
What if the "depth" of the data structure is unknown to me?
In addition to unknown keys, the "depth" of the data structure (i.e. how many nested objects) it has, might be unknown as well. How to access deeply nested properties usually depends on the exact data structure.
But if the data structure contains repeating patterns, e.g. the representation of a binary tree, the solution typically includes to recursively [Wikipedia] access each level of the data structure.
Here is an example to get the first leaf node of a binary tree:
function getLeaf(node) {
if (node.leftChild) {
return getLeaf(node.leftChild); // <- recursive call
}
else if (node.rightChild) {
return getLeaf(node.rightChild); // <- recursive call
}
else { // node must be a leaf node
return node;
}
}
const first_leaf = getLeaf(root);
const root = {
leftChild: {
leftChild: {
leftChild: null,
rightChild: null,
data: 42
},
rightChild: {
leftChild: null,
rightChild: null,
data: 5
}
},
rightChild: {
leftChild: {
leftChild: null,
rightChild: null,
data: 6
},
rightChild: {
leftChild: null,
rightChild: null,
data: 7
}
}
};
function getLeaf(node) {
if (node.leftChild) {
return getLeaf(node.leftChild);
} else if (node.rightChild) {
return getLeaf(node.rightChild);
} else { // node must be a leaf node
return node;
}
}
console.log(getLeaf(root).data);
A more generic way to access a nested data structure with unknown keys and depth is to test the type of the value and act accordingly.
Here is an example which adds all primitive values inside a nested data structure into an array (assuming it does not contain any functions). If we encounter an object (or array) we simply call toArray
again on that value (recursive call).
function toArray(obj) {
const result = ;
for (const prop in obj) {
const value = obj[prop];
if (typeof value === 'object') {
result.push(toArray(value)); // <- recursive call
}
else {
result.push(value);
}
}
return result;
}
const data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
function toArray(obj) {
const result = ;
for (const prop in obj) {
const value = obj[prop];
if (typeof value === 'object') {
result.push(toArray(value));
} else {
result.push(value);
}
}
return result;
}
console.log(toArray(data));
Helpers
Since the structure of a complex object or array is not necessarily obvious, we can inspect the value at each step to decide how to move further. console.log
[MDN] and console.dir
[MDN] help us doing this. For example (output of the Chrome console):
> console.log(data.items)
[ Object, Object ]
Here we see that that data.items
is an array with two elements which are both objects. In Chrome console the objects can even be expanded and inspected immediately.
> console.log(data.items[1])
Object
id: 2
name: "bar"
__proto__: Object
This tells us that data.items[1]
is an object, and after expanding it we see that it has three properties, id
, name
and __proto__
. The latter is an internal property used for the prototype chain of the object. The prototype chain and inheritance is out of scope for this answer, though.
3
Some of what's being linked here is really asking how to do this in jQuery, which to be fair does simplify 1 or 2 things here. Not sure whether to make this more of a megapost or answer those separately - the basics covered here on what's an object what's an array are usually what's really being asked... .
– Chris Moschini
Apr 2 '13 at 9:29
@felix-kling One thing... with nested objects, such aslet object = {a: 1, b: 2, c: { a: 3, b: 4 }};
, this returns an array containing an array for each nested object, in this case[ 1, 2, [ 3, 4 ] ]
Wouldn't it be better to to use concat in the recursive call instead of push ? (requiring result to be mutable)
– ElFitz
May 3 at 15:44
This is the most in-depth answer I have ever seen on Stack Overflow - and it answered my question! Thanks!
– William Jones
Nov 15 at 19:58
add a comment |
Preliminaries
JavaScript has only one data type which can contain multiple values: Object. An Array is a special form of object.
(Plain) Objects have the form
{key: value, key: value, ...}
Arrays have the form
[value, value, ...]
Both arrays and objects expose a key -> value
structure. Keys in an array must be numeric, whereas any string can be used as key in objects. The key-value pairs are also called the "properties".
Properties can be accessed either using dot notation
const value = obj.someProperty;
or bracket notation, if the property name would not be a valid JavaScript identifier name [spec], or the name is the value of a variable:
// the space is not a valid character in identifier names
const value = obj["some Property"];
// property name as variable
const name = "some Property";
const value = obj[name];
For that reason, array elements can only be accessed using bracket notation:
const value = arr[5]; // arr.5 would be a syntax error
// property name / index as variable
const x = 5;
const value = arr[x];
Wait... what about JSON?
JSON is a textual representation of data, just like XML, YAML, CSV, and others. To work with such data, it first has to be converted to JavaScript data types, i.e. arrays and objects (and how to work with those was just explained). How to parse JSON is explained in the question Parse JSON in JavaScript? .
Further reading material
How to access arrays and objects is fundamental JavaScript knowledge and therefore it is advisable to read the MDN JavaScript Guide, especially the sections
- Working with Objects
- Arrays
- Eloquent JavaScript - Data Structures
Accessing nested data structures
A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation.
Here is an example:
const data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
Let's assume we want to access the name
of the second item.
Here is how we can do it step-by-step:
As we can see data
is an object, hence we can access its properties using dot notation. The items
property is accessed as follows:
data.items
The value is an array, to access its second element, we have to use bracket notation:
data.items[1]
This value is an object and we use dot notation again to access the name
property. So we eventually get:
const item_name = data.items[1].name;
Alternatively, we could have used bracket notation for any of the properties, especially if the name contained characters that would have made it invalid for dot notation usage:
const item_name = data['items'][1]['name'];
I'm trying to access a property but I get only undefined
back?
Most of the time when you are getting undefined
, the object/array simply doesn't have a property with that name.
const foo = {bar: {baz: 42}};
console.log(foo.baz); // undefined
Use console.log
or console.dir
and inspect the structure of object / array. The property you are trying to access might be actually defined on a nested object / array.
console.log(foo.bar.baz); // 42
What if the property names are dynamic and I don't know them beforehand?
If the property names are unknown or we want to access all properties of an object / elements of an array, we can use the for...in
[MDN] loop for objects and the for
[MDN] loop for arrays to iterate over all properties / elements.
Objects
To iterate over all properties of data
, we can iterate over the object like so:
for (const prop in data) {
// `prop` contains the name of each property, i.e. `'code'` or `'items'`
// consequently, `data[prop]` refers to the value of each property, i.e.
// either `42` or the array
}
Depending on where the object comes from (and what you want to do), you might have to test in each iteration whether the property is really a property of the object, or it is an inherited property. You can do this with Object#hasOwnProperty
[MDN].
As alternative to for...in
with hasOwnProperty
, you can use Object.keys
[MDN] to get an array of property names:
Object.keys(data).forEach(function(prop) {
// `prop` is the property name
// `data[prop]` is the property value
});
Arrays
To iterate over all elements of the data.items
array, we use a for
loop:
for(let i = 0, l = data.items.length; i < l; i++) {
// `i` will take on the values `0`, `1`, `2`,..., i.e. in each iteration
// we can access the next element in the array with `data.items[i]`, example:
//
// var obj = data.items[i];
//
// Since each element is an object (in our example),
// we can now access the objects properties with `obj.id` and `obj.name`.
// We could also use `data.items[i].id`.
}
One could also use for...in
to iterate over arrays, but there are reasons why this should be avoided: Why is 'for(var item in list)' with arrays considered bad practice in JavaScript?.
With the increasing browser support of ECMAScript 5, the array method forEach
[MDN] becomes an interesting alternative as well:
data.items.forEach(function(value, index, array) {
// The callback is executed for each element in the array.
// `value` is the element itself (equivalent to `array[index]`)
// `index` will be the index of the element in the array
// `array` is a reference to the array itself (i.e. `data.items` in this case)
});
In environments supporting ES2015 (ES6), you can also use the for...of
[MDN] loop, which not only works for arrays, but for any iterable:
for (const item of data.items) {
// `item` is the array element, **not** the index
}
In each iteration, for...of
directly gives us the next element of the iterable, there is no "index" to access or use.
What if the "depth" of the data structure is unknown to me?
In addition to unknown keys, the "depth" of the data structure (i.e. how many nested objects) it has, might be unknown as well. How to access deeply nested properties usually depends on the exact data structure.
But if the data structure contains repeating patterns, e.g. the representation of a binary tree, the solution typically includes to recursively [Wikipedia] access each level of the data structure.
Here is an example to get the first leaf node of a binary tree:
function getLeaf(node) {
if (node.leftChild) {
return getLeaf(node.leftChild); // <- recursive call
}
else if (node.rightChild) {
return getLeaf(node.rightChild); // <- recursive call
}
else { // node must be a leaf node
return node;
}
}
const first_leaf = getLeaf(root);
const root = {
leftChild: {
leftChild: {
leftChild: null,
rightChild: null,
data: 42
},
rightChild: {
leftChild: null,
rightChild: null,
data: 5
}
},
rightChild: {
leftChild: {
leftChild: null,
rightChild: null,
data: 6
},
rightChild: {
leftChild: null,
rightChild: null,
data: 7
}
}
};
function getLeaf(node) {
if (node.leftChild) {
return getLeaf(node.leftChild);
} else if (node.rightChild) {
return getLeaf(node.rightChild);
} else { // node must be a leaf node
return node;
}
}
console.log(getLeaf(root).data);
A more generic way to access a nested data structure with unknown keys and depth is to test the type of the value and act accordingly.
Here is an example which adds all primitive values inside a nested data structure into an array (assuming it does not contain any functions). If we encounter an object (or array) we simply call toArray
again on that value (recursive call).
function toArray(obj) {
const result = ;
for (const prop in obj) {
const value = obj[prop];
if (typeof value === 'object') {
result.push(toArray(value)); // <- recursive call
}
else {
result.push(value);
}
}
return result;
}
const data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
function toArray(obj) {
const result = ;
for (const prop in obj) {
const value = obj[prop];
if (typeof value === 'object') {
result.push(toArray(value));
} else {
result.push(value);
}
}
return result;
}
console.log(toArray(data));
Helpers
Since the structure of a complex object or array is not necessarily obvious, we can inspect the value at each step to decide how to move further. console.log
[MDN] and console.dir
[MDN] help us doing this. For example (output of the Chrome console):
> console.log(data.items)
[ Object, Object ]
Here we see that that data.items
is an array with two elements which are both objects. In Chrome console the objects can even be expanded and inspected immediately.
> console.log(data.items[1])
Object
id: 2
name: "bar"
__proto__: Object
This tells us that data.items[1]
is an object, and after expanding it we see that it has three properties, id
, name
and __proto__
. The latter is an internal property used for the prototype chain of the object. The prototype chain and inheritance is out of scope for this answer, though.
Preliminaries
JavaScript has only one data type which can contain multiple values: Object. An Array is a special form of object.
(Plain) Objects have the form
{key: value, key: value, ...}
Arrays have the form
[value, value, ...]
Both arrays and objects expose a key -> value
structure. Keys in an array must be numeric, whereas any string can be used as key in objects. The key-value pairs are also called the "properties".
Properties can be accessed either using dot notation
const value = obj.someProperty;
or bracket notation, if the property name would not be a valid JavaScript identifier name [spec], or the name is the value of a variable:
// the space is not a valid character in identifier names
const value = obj["some Property"];
// property name as variable
const name = "some Property";
const value = obj[name];
For that reason, array elements can only be accessed using bracket notation:
const value = arr[5]; // arr.5 would be a syntax error
// property name / index as variable
const x = 5;
const value = arr[x];
Wait... what about JSON?
JSON is a textual representation of data, just like XML, YAML, CSV, and others. To work with such data, it first has to be converted to JavaScript data types, i.e. arrays and objects (and how to work with those was just explained). How to parse JSON is explained in the question Parse JSON in JavaScript? .
Further reading material
How to access arrays and objects is fundamental JavaScript knowledge and therefore it is advisable to read the MDN JavaScript Guide, especially the sections
- Working with Objects
- Arrays
- Eloquent JavaScript - Data Structures
Accessing nested data structures
A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation.
Here is an example:
const data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
Let's assume we want to access the name
of the second item.
Here is how we can do it step-by-step:
As we can see data
is an object, hence we can access its properties using dot notation. The items
property is accessed as follows:
data.items
The value is an array, to access its second element, we have to use bracket notation:
data.items[1]
This value is an object and we use dot notation again to access the name
property. So we eventually get:
const item_name = data.items[1].name;
Alternatively, we could have used bracket notation for any of the properties, especially if the name contained characters that would have made it invalid for dot notation usage:
const item_name = data['items'][1]['name'];
I'm trying to access a property but I get only undefined
back?
Most of the time when you are getting undefined
, the object/array simply doesn't have a property with that name.
const foo = {bar: {baz: 42}};
console.log(foo.baz); // undefined
Use console.log
or console.dir
and inspect the structure of object / array. The property you are trying to access might be actually defined on a nested object / array.
console.log(foo.bar.baz); // 42
What if the property names are dynamic and I don't know them beforehand?
If the property names are unknown or we want to access all properties of an object / elements of an array, we can use the for...in
[MDN] loop for objects and the for
[MDN] loop for arrays to iterate over all properties / elements.
Objects
To iterate over all properties of data
, we can iterate over the object like so:
for (const prop in data) {
// `prop` contains the name of each property, i.e. `'code'` or `'items'`
// consequently, `data[prop]` refers to the value of each property, i.e.
// either `42` or the array
}
Depending on where the object comes from (and what you want to do), you might have to test in each iteration whether the property is really a property of the object, or it is an inherited property. You can do this with Object#hasOwnProperty
[MDN].
As alternative to for...in
with hasOwnProperty
, you can use Object.keys
[MDN] to get an array of property names:
Object.keys(data).forEach(function(prop) {
// `prop` is the property name
// `data[prop]` is the property value
});
Arrays
To iterate over all elements of the data.items
array, we use a for
loop:
for(let i = 0, l = data.items.length; i < l; i++) {
// `i` will take on the values `0`, `1`, `2`,..., i.e. in each iteration
// we can access the next element in the array with `data.items[i]`, example:
//
// var obj = data.items[i];
//
// Since each element is an object (in our example),
// we can now access the objects properties with `obj.id` and `obj.name`.
// We could also use `data.items[i].id`.
}
One could also use for...in
to iterate over arrays, but there are reasons why this should be avoided: Why is 'for(var item in list)' with arrays considered bad practice in JavaScript?.
With the increasing browser support of ECMAScript 5, the array method forEach
[MDN] becomes an interesting alternative as well:
data.items.forEach(function(value, index, array) {
// The callback is executed for each element in the array.
// `value` is the element itself (equivalent to `array[index]`)
// `index` will be the index of the element in the array
// `array` is a reference to the array itself (i.e. `data.items` in this case)
});
In environments supporting ES2015 (ES6), you can also use the for...of
[MDN] loop, which not only works for arrays, but for any iterable:
for (const item of data.items) {
// `item` is the array element, **not** the index
}
In each iteration, for...of
directly gives us the next element of the iterable, there is no "index" to access or use.
What if the "depth" of the data structure is unknown to me?
In addition to unknown keys, the "depth" of the data structure (i.e. how many nested objects) it has, might be unknown as well. How to access deeply nested properties usually depends on the exact data structure.
But if the data structure contains repeating patterns, e.g. the representation of a binary tree, the solution typically includes to recursively [Wikipedia] access each level of the data structure.
Here is an example to get the first leaf node of a binary tree:
function getLeaf(node) {
if (node.leftChild) {
return getLeaf(node.leftChild); // <- recursive call
}
else if (node.rightChild) {
return getLeaf(node.rightChild); // <- recursive call
}
else { // node must be a leaf node
return node;
}
}
const first_leaf = getLeaf(root);
const root = {
leftChild: {
leftChild: {
leftChild: null,
rightChild: null,
data: 42
},
rightChild: {
leftChild: null,
rightChild: null,
data: 5
}
},
rightChild: {
leftChild: {
leftChild: null,
rightChild: null,
data: 6
},
rightChild: {
leftChild: null,
rightChild: null,
data: 7
}
}
};
function getLeaf(node) {
if (node.leftChild) {
return getLeaf(node.leftChild);
} else if (node.rightChild) {
return getLeaf(node.rightChild);
} else { // node must be a leaf node
return node;
}
}
console.log(getLeaf(root).data);
A more generic way to access a nested data structure with unknown keys and depth is to test the type of the value and act accordingly.
Here is an example which adds all primitive values inside a nested data structure into an array (assuming it does not contain any functions). If we encounter an object (or array) we simply call toArray
again on that value (recursive call).
function toArray(obj) {
const result = ;
for (const prop in obj) {
const value = obj[prop];
if (typeof value === 'object') {
result.push(toArray(value)); // <- recursive call
}
else {
result.push(value);
}
}
return result;
}
const data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
function toArray(obj) {
const result = ;
for (const prop in obj) {
const value = obj[prop];
if (typeof value === 'object') {
result.push(toArray(value));
} else {
result.push(value);
}
}
return result;
}
console.log(toArray(data));
Helpers
Since the structure of a complex object or array is not necessarily obvious, we can inspect the value at each step to decide how to move further. console.log
[MDN] and console.dir
[MDN] help us doing this. For example (output of the Chrome console):
> console.log(data.items)
[ Object, Object ]
Here we see that that data.items
is an array with two elements which are both objects. In Chrome console the objects can even be expanded and inspected immediately.
> console.log(data.items[1])
Object
id: 2
name: "bar"
__proto__: Object
This tells us that data.items[1]
is an object, and after expanding it we see that it has three properties, id
, name
and __proto__
. The latter is an internal property used for the prototype chain of the object. The prototype chain and inheritance is out of scope for this answer, though.
const root = {
leftChild: {
leftChild: {
leftChild: null,
rightChild: null,
data: 42
},
rightChild: {
leftChild: null,
rightChild: null,
data: 5
}
},
rightChild: {
leftChild: {
leftChild: null,
rightChild: null,
data: 6
},
rightChild: {
leftChild: null,
rightChild: null,
data: 7
}
}
};
function getLeaf(node) {
if (node.leftChild) {
return getLeaf(node.leftChild);
} else if (node.rightChild) {
return getLeaf(node.rightChild);
} else { // node must be a leaf node
return node;
}
}
console.log(getLeaf(root).data);
const root = {
leftChild: {
leftChild: {
leftChild: null,
rightChild: null,
data: 42
},
rightChild: {
leftChild: null,
rightChild: null,
data: 5
}
},
rightChild: {
leftChild: {
leftChild: null,
rightChild: null,
data: 6
},
rightChild: {
leftChild: null,
rightChild: null,
data: 7
}
}
};
function getLeaf(node) {
if (node.leftChild) {
return getLeaf(node.leftChild);
} else if (node.rightChild) {
return getLeaf(node.rightChild);
} else { // node must be a leaf node
return node;
}
}
console.log(getLeaf(root).data);
const data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
function toArray(obj) {
const result = ;
for (const prop in obj) {
const value = obj[prop];
if (typeof value === 'object') {
result.push(toArray(value));
} else {
result.push(value);
}
}
return result;
}
console.log(toArray(data));
const data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
function toArray(obj) {
const result = ;
for (const prop in obj) {
const value = obj[prop];
if (typeof value === 'object') {
result.push(toArray(value));
} else {
result.push(value);
}
}
return result;
}
console.log(toArray(data));
edited Jun 16 '17 at 19:10
community wiki
25 revs, 6 users 92%
Felix Kling
3
Some of what's being linked here is really asking how to do this in jQuery, which to be fair does simplify 1 or 2 things here. Not sure whether to make this more of a megapost or answer those separately - the basics covered here on what's an object what's an array are usually what's really being asked... .
– Chris Moschini
Apr 2 '13 at 9:29
@felix-kling One thing... with nested objects, such aslet object = {a: 1, b: 2, c: { a: 3, b: 4 }};
, this returns an array containing an array for each nested object, in this case[ 1, 2, [ 3, 4 ] ]
Wouldn't it be better to to use concat in the recursive call instead of push ? (requiring result to be mutable)
– ElFitz
May 3 at 15:44
This is the most in-depth answer I have ever seen on Stack Overflow - and it answered my question! Thanks!
– William Jones
Nov 15 at 19:58
add a comment |
3
Some of what's being linked here is really asking how to do this in jQuery, which to be fair does simplify 1 or 2 things here. Not sure whether to make this more of a megapost or answer those separately - the basics covered here on what's an object what's an array are usually what's really being asked... .
– Chris Moschini
Apr 2 '13 at 9:29
@felix-kling One thing... with nested objects, such aslet object = {a: 1, b: 2, c: { a: 3, b: 4 }};
, this returns an array containing an array for each nested object, in this case[ 1, 2, [ 3, 4 ] ]
Wouldn't it be better to to use concat in the recursive call instead of push ? (requiring result to be mutable)
– ElFitz
May 3 at 15:44
This is the most in-depth answer I have ever seen on Stack Overflow - and it answered my question! Thanks!
– William Jones
Nov 15 at 19:58
3
3
Some of what's being linked here is really asking how to do this in jQuery, which to be fair does simplify 1 or 2 things here. Not sure whether to make this more of a megapost or answer those separately - the basics covered here on what's an object what's an array are usually what's really being asked... .
– Chris Moschini
Apr 2 '13 at 9:29
Some of what's being linked here is really asking how to do this in jQuery, which to be fair does simplify 1 or 2 things here. Not sure whether to make this more of a megapost or answer those separately - the basics covered here on what's an object what's an array are usually what's really being asked... .
– Chris Moschini
Apr 2 '13 at 9:29
@felix-kling One thing... with nested objects, such as
let object = {a: 1, b: 2, c: { a: 3, b: 4 }};
, this returns an array containing an array for each nested object, in this case [ 1, 2, [ 3, 4 ] ]
Wouldn't it be better to to use concat in the recursive call instead of push ? (requiring result to be mutable)– ElFitz
May 3 at 15:44
@felix-kling One thing... with nested objects, such as
let object = {a: 1, b: 2, c: { a: 3, b: 4 }};
, this returns an array containing an array for each nested object, in this case [ 1, 2, [ 3, 4 ] ]
Wouldn't it be better to to use concat in the recursive call instead of push ? (requiring result to be mutable)– ElFitz
May 3 at 15:44
This is the most in-depth answer I have ever seen on Stack Overflow - and it answered my question! Thanks!
– William Jones
Nov 15 at 19:58
This is the most in-depth answer I have ever seen on Stack Overflow - and it answered my question! Thanks!
– William Jones
Nov 15 at 19:58
add a comment |
You can access it this way
data.items[1].name
or
data["items"][1]["name"]
Both ways are equal.
Yea but you can't do data["items"].1.name
– neaumusic
Oct 21 '15 at 19:01
1
First is far more intuitive, readable and shorter ;) I prefer using bracket property syntax only when the property name is variable.
– DanteTheSmith
Oct 2 '17 at 11:59
add a comment |
You can access it this way
data.items[1].name
or
data["items"][1]["name"]
Both ways are equal.
Yea but you can't do data["items"].1.name
– neaumusic
Oct 21 '15 at 19:01
1
First is far more intuitive, readable and shorter ;) I prefer using bracket property syntax only when the property name is variable.
– DanteTheSmith
Oct 2 '17 at 11:59
add a comment |
You can access it this way
data.items[1].name
or
data["items"][1]["name"]
Both ways are equal.
You can access it this way
data.items[1].name
or
data["items"][1]["name"]
Both ways are equal.
answered May 14 '13 at 3:29
vitmalina
93385
93385
Yea but you can't do data["items"].1.name
– neaumusic
Oct 21 '15 at 19:01
1
First is far more intuitive, readable and shorter ;) I prefer using bracket property syntax only when the property name is variable.
– DanteTheSmith
Oct 2 '17 at 11:59
add a comment |
Yea but you can't do data["items"].1.name
– neaumusic
Oct 21 '15 at 19:01
1
First is far more intuitive, readable and shorter ;) I prefer using bracket property syntax only when the property name is variable.
– DanteTheSmith
Oct 2 '17 at 11:59
Yea but you can't do data["items"].1.name
– neaumusic
Oct 21 '15 at 19:01
Yea but you can't do data["items"].1.name
– neaumusic
Oct 21 '15 at 19:01
1
1
First is far more intuitive, readable and shorter ;) I prefer using bracket property syntax only when the property name is variable.
– DanteTheSmith
Oct 2 '17 at 11:59
First is far more intuitive, readable and shorter ;) I prefer using bracket property syntax only when the property name is variable.
– DanteTheSmith
Oct 2 '17 at 11:59
add a comment |
In case you're trying to access an item
from the example structure by id
or name
, without knowing it's position in the array, the easiest way to do it would be to use underscore.js library:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
_.find(data.items, function(item) {
return item.id === 2;
});
// Object {id: 2, name: "bar"}
From my experience, using higher order functions instead of for
or for..in
loops results in code that is easier to reason about, and hence more maintainable.
Just my 2 cents.
add a comment |
In case you're trying to access an item
from the example structure by id
or name
, without knowing it's position in the array, the easiest way to do it would be to use underscore.js library:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
_.find(data.items, function(item) {
return item.id === 2;
});
// Object {id: 2, name: "bar"}
From my experience, using higher order functions instead of for
or for..in
loops results in code that is easier to reason about, and hence more maintainable.
Just my 2 cents.
add a comment |
In case you're trying to access an item
from the example structure by id
or name
, without knowing it's position in the array, the easiest way to do it would be to use underscore.js library:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
_.find(data.items, function(item) {
return item.id === 2;
});
// Object {id: 2, name: "bar"}
From my experience, using higher order functions instead of for
or for..in
loops results in code that is easier to reason about, and hence more maintainable.
Just my 2 cents.
In case you're trying to access an item
from the example structure by id
or name
, without knowing it's position in the array, the easiest way to do it would be to use underscore.js library:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
_.find(data.items, function(item) {
return item.id === 2;
});
// Object {id: 2, name: "bar"}
From my experience, using higher order functions instead of for
or for..in
loops results in code that is easier to reason about, and hence more maintainable.
Just my 2 cents.
edited Jan 13 '14 at 10:25
lukas.pukenis
7,579103269
7,579103269
answered Jun 29 '13 at 9:15
holographic-principle
18.4k93960
18.4k93960
add a comment |
add a comment |
At times, accessing a nested object using a string can be desirable. The simple approach is the first level, for example
var obj = { hello: "world" };
var key = "hello";
alert(obj[key]);//world
But this is often not the case with complex json. As json becomes more complex, the approaches for finding values inside of the json also become complex. A recursive approach for navigating the json is best, and how that recursion is leveraged will depend on the type of data being searched for. If there are conditional statements involved, a json search can be a good tool to use.
If the property being accessed is already known, but the path is complex, for example in this object
var obj = {
arr: [
{ id: 1, name: "larry" },
{ id: 2, name: "curly" },
{ id: 3, name: "moe" }
]
};
And you know you want to get the first result of the array in the object, perhaps you would like to use
var moe = obj["arr[0].name"];
However, that will cause an exception as there is no property of object with that name. The solution to be able to use this would be to flatten the tree aspect of the object. This can be done recursively.
function flatten(obj){
var root = {};
(function tree(obj, index){
var suffix = toString.call(obj) == "[object Array]" ? "]" : "";
for(var key in obj){
if(!obj.hasOwnProperty(key))continue;
root[index+key+suffix] = obj[key];
if( toString.call(obj[key]) == "[object Array]" )tree(obj[key],index+key+suffix+"[");
if( toString.call(obj[key]) == "[object Object]" )tree(obj[key],index+key+suffix+".");
}
})(obj,"");
return root;
}
Now, the complex object can be flattened
var obj = previous definition;
var flat = flatten(obj);
var moe = flat["arr[0].name"];//moe
Here is a jsFiddle Demo
of this approach being used.
WTH would you want to useobj["arr[0].name"]
instead ofobj.arr[0].name
? You hardly need/want to deal with flattened objects except for serialisation.
– Bergi
Aug 19 '14 at 16:00
@Bergi - I see this question commonly, and since this is being used canonically, I posted an answer to that version of it. If it is avoidable it is much faster to use obj.arr[0].name, but sometimes people want to pass string accessors around and this is an example of doing that.
– Travis J
Aug 19 '14 at 17:28
Urgh. Still, there's hardly a reason to flatten the complete object only to use a single string path, you could simply parse that and do a dynamic lookup.
– Bergi
Aug 19 '14 at 17:29
add a comment |
At times, accessing a nested object using a string can be desirable. The simple approach is the first level, for example
var obj = { hello: "world" };
var key = "hello";
alert(obj[key]);//world
But this is often not the case with complex json. As json becomes more complex, the approaches for finding values inside of the json also become complex. A recursive approach for navigating the json is best, and how that recursion is leveraged will depend on the type of data being searched for. If there are conditional statements involved, a json search can be a good tool to use.
If the property being accessed is already known, but the path is complex, for example in this object
var obj = {
arr: [
{ id: 1, name: "larry" },
{ id: 2, name: "curly" },
{ id: 3, name: "moe" }
]
};
And you know you want to get the first result of the array in the object, perhaps you would like to use
var moe = obj["arr[0].name"];
However, that will cause an exception as there is no property of object with that name. The solution to be able to use this would be to flatten the tree aspect of the object. This can be done recursively.
function flatten(obj){
var root = {};
(function tree(obj, index){
var suffix = toString.call(obj) == "[object Array]" ? "]" : "";
for(var key in obj){
if(!obj.hasOwnProperty(key))continue;
root[index+key+suffix] = obj[key];
if( toString.call(obj[key]) == "[object Array]" )tree(obj[key],index+key+suffix+"[");
if( toString.call(obj[key]) == "[object Object]" )tree(obj[key],index+key+suffix+".");
}
})(obj,"");
return root;
}
Now, the complex object can be flattened
var obj = previous definition;
var flat = flatten(obj);
var moe = flat["arr[0].name"];//moe
Here is a jsFiddle Demo
of this approach being used.
WTH would you want to useobj["arr[0].name"]
instead ofobj.arr[0].name
? You hardly need/want to deal with flattened objects except for serialisation.
– Bergi
Aug 19 '14 at 16:00
@Bergi - I see this question commonly, and since this is being used canonically, I posted an answer to that version of it. If it is avoidable it is much faster to use obj.arr[0].name, but sometimes people want to pass string accessors around and this is an example of doing that.
– Travis J
Aug 19 '14 at 17:28
Urgh. Still, there's hardly a reason to flatten the complete object only to use a single string path, you could simply parse that and do a dynamic lookup.
– Bergi
Aug 19 '14 at 17:29
add a comment |
At times, accessing a nested object using a string can be desirable. The simple approach is the first level, for example
var obj = { hello: "world" };
var key = "hello";
alert(obj[key]);//world
But this is often not the case with complex json. As json becomes more complex, the approaches for finding values inside of the json also become complex. A recursive approach for navigating the json is best, and how that recursion is leveraged will depend on the type of data being searched for. If there are conditional statements involved, a json search can be a good tool to use.
If the property being accessed is already known, but the path is complex, for example in this object
var obj = {
arr: [
{ id: 1, name: "larry" },
{ id: 2, name: "curly" },
{ id: 3, name: "moe" }
]
};
And you know you want to get the first result of the array in the object, perhaps you would like to use
var moe = obj["arr[0].name"];
However, that will cause an exception as there is no property of object with that name. The solution to be able to use this would be to flatten the tree aspect of the object. This can be done recursively.
function flatten(obj){
var root = {};
(function tree(obj, index){
var suffix = toString.call(obj) == "[object Array]" ? "]" : "";
for(var key in obj){
if(!obj.hasOwnProperty(key))continue;
root[index+key+suffix] = obj[key];
if( toString.call(obj[key]) == "[object Array]" )tree(obj[key],index+key+suffix+"[");
if( toString.call(obj[key]) == "[object Object]" )tree(obj[key],index+key+suffix+".");
}
})(obj,"");
return root;
}
Now, the complex object can be flattened
var obj = previous definition;
var flat = flatten(obj);
var moe = flat["arr[0].name"];//moe
Here is a jsFiddle Demo
of this approach being used.
At times, accessing a nested object using a string can be desirable. The simple approach is the first level, for example
var obj = { hello: "world" };
var key = "hello";
alert(obj[key]);//world
But this is often not the case with complex json. As json becomes more complex, the approaches for finding values inside of the json also become complex. A recursive approach for navigating the json is best, and how that recursion is leveraged will depend on the type of data being searched for. If there are conditional statements involved, a json search can be a good tool to use.
If the property being accessed is already known, but the path is complex, for example in this object
var obj = {
arr: [
{ id: 1, name: "larry" },
{ id: 2, name: "curly" },
{ id: 3, name: "moe" }
]
};
And you know you want to get the first result of the array in the object, perhaps you would like to use
var moe = obj["arr[0].name"];
However, that will cause an exception as there is no property of object with that name. The solution to be able to use this would be to flatten the tree aspect of the object. This can be done recursively.
function flatten(obj){
var root = {};
(function tree(obj, index){
var suffix = toString.call(obj) == "[object Array]" ? "]" : "";
for(var key in obj){
if(!obj.hasOwnProperty(key))continue;
root[index+key+suffix] = obj[key];
if( toString.call(obj[key]) == "[object Array]" )tree(obj[key],index+key+suffix+"[");
if( toString.call(obj[key]) == "[object Object]" )tree(obj[key],index+key+suffix+".");
}
})(obj,"");
return root;
}
Now, the complex object can be flattened
var obj = previous definition;
var flat = flatten(obj);
var moe = flat["arr[0].name"];//moe
Here is a jsFiddle Demo
of this approach being used.
edited May 23 '17 at 12:10
Community♦
11
11
answered Aug 18 '14 at 19:20
Travis J
63.6k28148222
63.6k28148222
WTH would you want to useobj["arr[0].name"]
instead ofobj.arr[0].name
? You hardly need/want to deal with flattened objects except for serialisation.
– Bergi
Aug 19 '14 at 16:00
@Bergi - I see this question commonly, and since this is being used canonically, I posted an answer to that version of it. If it is avoidable it is much faster to use obj.arr[0].name, but sometimes people want to pass string accessors around and this is an example of doing that.
– Travis J
Aug 19 '14 at 17:28
Urgh. Still, there's hardly a reason to flatten the complete object only to use a single string path, you could simply parse that and do a dynamic lookup.
– Bergi
Aug 19 '14 at 17:29
add a comment |
WTH would you want to useobj["arr[0].name"]
instead ofobj.arr[0].name
? You hardly need/want to deal with flattened objects except for serialisation.
– Bergi
Aug 19 '14 at 16:00
@Bergi - I see this question commonly, and since this is being used canonically, I posted an answer to that version of it. If it is avoidable it is much faster to use obj.arr[0].name, but sometimes people want to pass string accessors around and this is an example of doing that.
– Travis J
Aug 19 '14 at 17:28
Urgh. Still, there's hardly a reason to flatten the complete object only to use a single string path, you could simply parse that and do a dynamic lookup.
– Bergi
Aug 19 '14 at 17:29
WTH would you want to use
obj["arr[0].name"]
instead of obj.arr[0].name
? You hardly need/want to deal with flattened objects except for serialisation.– Bergi
Aug 19 '14 at 16:00
WTH would you want to use
obj["arr[0].name"]
instead of obj.arr[0].name
? You hardly need/want to deal with flattened objects except for serialisation.– Bergi
Aug 19 '14 at 16:00
@Bergi - I see this question commonly, and since this is being used canonically, I posted an answer to that version of it. If it is avoidable it is much faster to use obj.arr[0].name, but sometimes people want to pass string accessors around and this is an example of doing that.
– Travis J
Aug 19 '14 at 17:28
@Bergi - I see this question commonly, and since this is being used canonically, I posted an answer to that version of it. If it is avoidable it is much faster to use obj.arr[0].name, but sometimes people want to pass string accessors around and this is an example of doing that.
– Travis J
Aug 19 '14 at 17:28
Urgh. Still, there's hardly a reason to flatten the complete object only to use a single string path, you could simply parse that and do a dynamic lookup.
– Bergi
Aug 19 '14 at 17:29
Urgh. Still, there's hardly a reason to flatten the complete object only to use a single string path, you could simply parse that and do a dynamic lookup.
– Bergi
Aug 19 '14 at 17:29
add a comment |
Objects and arrays has a lot of built-in methods that can help you with processing data.
Note: in many of the examples I'm using arrow functions. They are similar to function expressions, but they bind the this
value lexically.
Object.keys()
, Object.values()
(ES 2017) and Object.entries()
(ES 2017)
Object.keys()
returns an array of object's keys, Object.values()
returns an array of object's values, and Object.entries()
returns an array of object's keys and corresponding values in a format [key, value]
.
const obj = {
a: 1
,b: 2
,c: 3
}
console.log(Object.keys(obj)) // ['a', 'b', 'c']
console.log(Object.values(obj)) // [1, 2, 3]
console.log(Object.entries(obj)) // [['a', 1], ['b', 2], ['c', 3]]
Object.entries()
with a for-of loop and destructuring assignment
const obj = {
a: 1
,b: 2
,c: 3
}
for (const [key, value] of Object.entries(obj)) {
console.log(`key: ${key}, value: ${value}`)
}
It's very convenient to iterate the result of Object.entries()
with a for-of loop and destructuring assignment.
For-of loop lets you iterate array elements. The syntax is for (const element of array)
(we can replace const
with var
or let
, but it's better to use const
if we don't intend to modify element
).
Destructuring assignment lets you extract values from an array or an object and assign them to variables. In this case const [key, value]
means that instead of assigning the [key, value]
array to element
, we assign the first element of that array to key
and the second element to value
. It is equivalent to this:
for (const element of Object.entries(obj)) {
const key = element[0]
,value = element[1]
}
As you can see, destructuring makes this a lot simpler.
Array.prototype.every()
and Array.prototype.some()
The every()
method returns true
if the specified callback function returns true
for every element of the array. The some()
method returns true
if the specified callback function returns true
for some (at least one) element.
const arr = [1, 2, 3]
// true, because every element is greater than 0
console.log(arr.every(x => x > 0))
// false, because 3^2 is greater than 5
console.log(arr.every(x => Math.pow(x, 2) < 5))
// true, because 2 is even (the remainder from dividing by 2 is 0)
console.log(arr.some(x => x % 2 === 0))
// false, because none of the elements is equal to 5
console.log(arr.some(x => x === 5))
Array.prototype.find()
and Array.prototype.filter()
The find()
methods returns the first element which satisfies the provided callback function. The filter()
method returns an array of all elements which satisfies the provided callback function.
const arr = [1, 2, 3]
// 2, because 2^2 !== 2
console.log(arr.find(x => x !== Math.pow(x, 2)))
// 1, because it's the first element
console.log(arr.find(x => true))
// undefined, because none of the elements equals 7
console.log(arr.find(x => x === 7))
// [2, 3], because these elements are greater than 1
console.log(arr.filter(x => x > 1))
// [1, 2, 3], because the function returns true for all elements
console.log(arr.filter(x => true))
// , because none of the elements equals neither 6 nor 7
console.log(arr.filter(x => x === 6 || x === 7))
Array.prototype.map()
The map()
method returns an array with the results of calling a provided callback function on the array elements.
const arr = [1, 2, 3]
console.log(arr.map(x => x + 1)) // [2, 3, 4]
console.log(arr.map(x => String.fromCharCode(96 + x))) // ['a', 'b', 'c']
console.log(arr.map(x => x)) // [1, 2, 3] (no-op)
console.log(arr.map(x => Math.pow(x, 2))) // [1, 4, 9]
console.log(arr.map(String)) // ['1', '2', '3']
Array.prototype.reduce()
The reduce()
method reduces an array to a single value by calling the provided callback function with two elements.
const arr = [1, 2, 3]
// Sum of array elements.
console.log(arr.reduce((a, b) => a + b)) // 6
// The largest number in the array.
console.log(arr.reduce((a, b) => a > b ? a : b)) // 3
The reduce()
method takes an optional second parameter, which is the initial value. This is useful when the array on which you call reduce()
can has zero or one elements. For example, if we wanted to create a function sum()
which takes an array as an argument and returns the sum of all elements, we could write it like that:
const sum = arr => arr.reduce((a, b) => a + b, 0)
console.log(sum()) // 0
console.log(sum([4])) // 4
console.log(sum([2, 5])) // 7
add a comment |
Objects and arrays has a lot of built-in methods that can help you with processing data.
Note: in many of the examples I'm using arrow functions. They are similar to function expressions, but they bind the this
value lexically.
Object.keys()
, Object.values()
(ES 2017) and Object.entries()
(ES 2017)
Object.keys()
returns an array of object's keys, Object.values()
returns an array of object's values, and Object.entries()
returns an array of object's keys and corresponding values in a format [key, value]
.
const obj = {
a: 1
,b: 2
,c: 3
}
console.log(Object.keys(obj)) // ['a', 'b', 'c']
console.log(Object.values(obj)) // [1, 2, 3]
console.log(Object.entries(obj)) // [['a', 1], ['b', 2], ['c', 3]]
Object.entries()
with a for-of loop and destructuring assignment
const obj = {
a: 1
,b: 2
,c: 3
}
for (const [key, value] of Object.entries(obj)) {
console.log(`key: ${key}, value: ${value}`)
}
It's very convenient to iterate the result of Object.entries()
with a for-of loop and destructuring assignment.
For-of loop lets you iterate array elements. The syntax is for (const element of array)
(we can replace const
with var
or let
, but it's better to use const
if we don't intend to modify element
).
Destructuring assignment lets you extract values from an array or an object and assign them to variables. In this case const [key, value]
means that instead of assigning the [key, value]
array to element
, we assign the first element of that array to key
and the second element to value
. It is equivalent to this:
for (const element of Object.entries(obj)) {
const key = element[0]
,value = element[1]
}
As you can see, destructuring makes this a lot simpler.
Array.prototype.every()
and Array.prototype.some()
The every()
method returns true
if the specified callback function returns true
for every element of the array. The some()
method returns true
if the specified callback function returns true
for some (at least one) element.
const arr = [1, 2, 3]
// true, because every element is greater than 0
console.log(arr.every(x => x > 0))
// false, because 3^2 is greater than 5
console.log(arr.every(x => Math.pow(x, 2) < 5))
// true, because 2 is even (the remainder from dividing by 2 is 0)
console.log(arr.some(x => x % 2 === 0))
// false, because none of the elements is equal to 5
console.log(arr.some(x => x === 5))
Array.prototype.find()
and Array.prototype.filter()
The find()
methods returns the first element which satisfies the provided callback function. The filter()
method returns an array of all elements which satisfies the provided callback function.
const arr = [1, 2, 3]
// 2, because 2^2 !== 2
console.log(arr.find(x => x !== Math.pow(x, 2)))
// 1, because it's the first element
console.log(arr.find(x => true))
// undefined, because none of the elements equals 7
console.log(arr.find(x => x === 7))
// [2, 3], because these elements are greater than 1
console.log(arr.filter(x => x > 1))
// [1, 2, 3], because the function returns true for all elements
console.log(arr.filter(x => true))
// , because none of the elements equals neither 6 nor 7
console.log(arr.filter(x => x === 6 || x === 7))
Array.prototype.map()
The map()
method returns an array with the results of calling a provided callback function on the array elements.
const arr = [1, 2, 3]
console.log(arr.map(x => x + 1)) // [2, 3, 4]
console.log(arr.map(x => String.fromCharCode(96 + x))) // ['a', 'b', 'c']
console.log(arr.map(x => x)) // [1, 2, 3] (no-op)
console.log(arr.map(x => Math.pow(x, 2))) // [1, 4, 9]
console.log(arr.map(String)) // ['1', '2', '3']
Array.prototype.reduce()
The reduce()
method reduces an array to a single value by calling the provided callback function with two elements.
const arr = [1, 2, 3]
// Sum of array elements.
console.log(arr.reduce((a, b) => a + b)) // 6
// The largest number in the array.
console.log(arr.reduce((a, b) => a > b ? a : b)) // 3
The reduce()
method takes an optional second parameter, which is the initial value. This is useful when the array on which you call reduce()
can has zero or one elements. For example, if we wanted to create a function sum()
which takes an array as an argument and returns the sum of all elements, we could write it like that:
const sum = arr => arr.reduce((a, b) => a + b, 0)
console.log(sum()) // 0
console.log(sum([4])) // 4
console.log(sum([2, 5])) // 7
add a comment |
Objects and arrays has a lot of built-in methods that can help you with processing data.
Note: in many of the examples I'm using arrow functions. They are similar to function expressions, but they bind the this
value lexically.
Object.keys()
, Object.values()
(ES 2017) and Object.entries()
(ES 2017)
Object.keys()
returns an array of object's keys, Object.values()
returns an array of object's values, and Object.entries()
returns an array of object's keys and corresponding values in a format [key, value]
.
const obj = {
a: 1
,b: 2
,c: 3
}
console.log(Object.keys(obj)) // ['a', 'b', 'c']
console.log(Object.values(obj)) // [1, 2, 3]
console.log(Object.entries(obj)) // [['a', 1], ['b', 2], ['c', 3]]
Object.entries()
with a for-of loop and destructuring assignment
const obj = {
a: 1
,b: 2
,c: 3
}
for (const [key, value] of Object.entries(obj)) {
console.log(`key: ${key}, value: ${value}`)
}
It's very convenient to iterate the result of Object.entries()
with a for-of loop and destructuring assignment.
For-of loop lets you iterate array elements. The syntax is for (const element of array)
(we can replace const
with var
or let
, but it's better to use const
if we don't intend to modify element
).
Destructuring assignment lets you extract values from an array or an object and assign them to variables. In this case const [key, value]
means that instead of assigning the [key, value]
array to element
, we assign the first element of that array to key
and the second element to value
. It is equivalent to this:
for (const element of Object.entries(obj)) {
const key = element[0]
,value = element[1]
}
As you can see, destructuring makes this a lot simpler.
Array.prototype.every()
and Array.prototype.some()
The every()
method returns true
if the specified callback function returns true
for every element of the array. The some()
method returns true
if the specified callback function returns true
for some (at least one) element.
const arr = [1, 2, 3]
// true, because every element is greater than 0
console.log(arr.every(x => x > 0))
// false, because 3^2 is greater than 5
console.log(arr.every(x => Math.pow(x, 2) < 5))
// true, because 2 is even (the remainder from dividing by 2 is 0)
console.log(arr.some(x => x % 2 === 0))
// false, because none of the elements is equal to 5
console.log(arr.some(x => x === 5))
Array.prototype.find()
and Array.prototype.filter()
The find()
methods returns the first element which satisfies the provided callback function. The filter()
method returns an array of all elements which satisfies the provided callback function.
const arr = [1, 2, 3]
// 2, because 2^2 !== 2
console.log(arr.find(x => x !== Math.pow(x, 2)))
// 1, because it's the first element
console.log(arr.find(x => true))
// undefined, because none of the elements equals 7
console.log(arr.find(x => x === 7))
// [2, 3], because these elements are greater than 1
console.log(arr.filter(x => x > 1))
// [1, 2, 3], because the function returns true for all elements
console.log(arr.filter(x => true))
// , because none of the elements equals neither 6 nor 7
console.log(arr.filter(x => x === 6 || x === 7))
Array.prototype.map()
The map()
method returns an array with the results of calling a provided callback function on the array elements.
const arr = [1, 2, 3]
console.log(arr.map(x => x + 1)) // [2, 3, 4]
console.log(arr.map(x => String.fromCharCode(96 + x))) // ['a', 'b', 'c']
console.log(arr.map(x => x)) // [1, 2, 3] (no-op)
console.log(arr.map(x => Math.pow(x, 2))) // [1, 4, 9]
console.log(arr.map(String)) // ['1', '2', '3']
Array.prototype.reduce()
The reduce()
method reduces an array to a single value by calling the provided callback function with two elements.
const arr = [1, 2, 3]
// Sum of array elements.
console.log(arr.reduce((a, b) => a + b)) // 6
// The largest number in the array.
console.log(arr.reduce((a, b) => a > b ? a : b)) // 3
The reduce()
method takes an optional second parameter, which is the initial value. This is useful when the array on which you call reduce()
can has zero or one elements. For example, if we wanted to create a function sum()
which takes an array as an argument and returns the sum of all elements, we could write it like that:
const sum = arr => arr.reduce((a, b) => a + b, 0)
console.log(sum()) // 0
console.log(sum([4])) // 4
console.log(sum([2, 5])) // 7
Objects and arrays has a lot of built-in methods that can help you with processing data.
Note: in many of the examples I'm using arrow functions. They are similar to function expressions, but they bind the this
value lexically.
Object.keys()
, Object.values()
(ES 2017) and Object.entries()
(ES 2017)
Object.keys()
returns an array of object's keys, Object.values()
returns an array of object's values, and Object.entries()
returns an array of object's keys and corresponding values in a format [key, value]
.
const obj = {
a: 1
,b: 2
,c: 3
}
console.log(Object.keys(obj)) // ['a', 'b', 'c']
console.log(Object.values(obj)) // [1, 2, 3]
console.log(Object.entries(obj)) // [['a', 1], ['b', 2], ['c', 3]]
Object.entries()
with a for-of loop and destructuring assignment
const obj = {
a: 1
,b: 2
,c: 3
}
for (const [key, value] of Object.entries(obj)) {
console.log(`key: ${key}, value: ${value}`)
}
It's very convenient to iterate the result of Object.entries()
with a for-of loop and destructuring assignment.
For-of loop lets you iterate array elements. The syntax is for (const element of array)
(we can replace const
with var
or let
, but it's better to use const
if we don't intend to modify element
).
Destructuring assignment lets you extract values from an array or an object and assign them to variables. In this case const [key, value]
means that instead of assigning the [key, value]
array to element
, we assign the first element of that array to key
and the second element to value
. It is equivalent to this:
for (const element of Object.entries(obj)) {
const key = element[0]
,value = element[1]
}
As you can see, destructuring makes this a lot simpler.
Array.prototype.every()
and Array.prototype.some()
The every()
method returns true
if the specified callback function returns true
for every element of the array. The some()
method returns true
if the specified callback function returns true
for some (at least one) element.
const arr = [1, 2, 3]
// true, because every element is greater than 0
console.log(arr.every(x => x > 0))
// false, because 3^2 is greater than 5
console.log(arr.every(x => Math.pow(x, 2) < 5))
// true, because 2 is even (the remainder from dividing by 2 is 0)
console.log(arr.some(x => x % 2 === 0))
// false, because none of the elements is equal to 5
console.log(arr.some(x => x === 5))
Array.prototype.find()
and Array.prototype.filter()
The find()
methods returns the first element which satisfies the provided callback function. The filter()
method returns an array of all elements which satisfies the provided callback function.
const arr = [1, 2, 3]
// 2, because 2^2 !== 2
console.log(arr.find(x => x !== Math.pow(x, 2)))
// 1, because it's the first element
console.log(arr.find(x => true))
// undefined, because none of the elements equals 7
console.log(arr.find(x => x === 7))
// [2, 3], because these elements are greater than 1
console.log(arr.filter(x => x > 1))
// [1, 2, 3], because the function returns true for all elements
console.log(arr.filter(x => true))
// , because none of the elements equals neither 6 nor 7
console.log(arr.filter(x => x === 6 || x === 7))
Array.prototype.map()
The map()
method returns an array with the results of calling a provided callback function on the array elements.
const arr = [1, 2, 3]
console.log(arr.map(x => x + 1)) // [2, 3, 4]
console.log(arr.map(x => String.fromCharCode(96 + x))) // ['a', 'b', 'c']
console.log(arr.map(x => x)) // [1, 2, 3] (no-op)
console.log(arr.map(x => Math.pow(x, 2))) // [1, 4, 9]
console.log(arr.map(String)) // ['1', '2', '3']
Array.prototype.reduce()
The reduce()
method reduces an array to a single value by calling the provided callback function with two elements.
const arr = [1, 2, 3]
// Sum of array elements.
console.log(arr.reduce((a, b) => a + b)) // 6
// The largest number in the array.
console.log(arr.reduce((a, b) => a > b ? a : b)) // 3
The reduce()
method takes an optional second parameter, which is the initial value. This is useful when the array on which you call reduce()
can has zero or one elements. For example, if we wanted to create a function sum()
which takes an array as an argument and returns the sum of all elements, we could write it like that:
const sum = arr => arr.reduce((a, b) => a + b, 0)
console.log(sum()) // 0
console.log(sum([4])) // 4
console.log(sum([2, 5])) // 7
const obj = {
a: 1
,b: 2
,c: 3
}
console.log(Object.keys(obj)) // ['a', 'b', 'c']
console.log(Object.values(obj)) // [1, 2, 3]
console.log(Object.entries(obj)) // [['a', 1], ['b', 2], ['c', 3]]
const obj = {
a: 1
,b: 2
,c: 3
}
console.log(Object.keys(obj)) // ['a', 'b', 'c']
console.log(Object.values(obj)) // [1, 2, 3]
console.log(Object.entries(obj)) // [['a', 1], ['b', 2], ['c', 3]]
const obj = {
a: 1
,b: 2
,c: 3
}
for (const [key, value] of Object.entries(obj)) {
console.log(`key: ${key}, value: ${value}`)
}
const obj = {
a: 1
,b: 2
,c: 3
}
for (const [key, value] of Object.entries(obj)) {
console.log(`key: ${key}, value: ${value}`)
}
const arr = [1, 2, 3]
// true, because every element is greater than 0
console.log(arr.every(x => x > 0))
// false, because 3^2 is greater than 5
console.log(arr.every(x => Math.pow(x, 2) < 5))
// true, because 2 is even (the remainder from dividing by 2 is 0)
console.log(arr.some(x => x % 2 === 0))
// false, because none of the elements is equal to 5
console.log(arr.some(x => x === 5))
const arr = [1, 2, 3]
// true, because every element is greater than 0
console.log(arr.every(x => x > 0))
// false, because 3^2 is greater than 5
console.log(arr.every(x => Math.pow(x, 2) < 5))
// true, because 2 is even (the remainder from dividing by 2 is 0)
console.log(arr.some(x => x % 2 === 0))
// false, because none of the elements is equal to 5
console.log(arr.some(x => x === 5))
const arr = [1, 2, 3]
// 2, because 2^2 !== 2
console.log(arr.find(x => x !== Math.pow(x, 2)))
// 1, because it's the first element
console.log(arr.find(x => true))
// undefined, because none of the elements equals 7
console.log(arr.find(x => x === 7))
// [2, 3], because these elements are greater than 1
console.log(arr.filter(x => x > 1))
// [1, 2, 3], because the function returns true for all elements
console.log(arr.filter(x => true))
// , because none of the elements equals neither 6 nor 7
console.log(arr.filter(x => x === 6 || x === 7))
const arr = [1, 2, 3]
// 2, because 2^2 !== 2
console.log(arr.find(x => x !== Math.pow(x, 2)))
// 1, because it's the first element
console.log(arr.find(x => true))
// undefined, because none of the elements equals 7
console.log(arr.find(x => x === 7))
// [2, 3], because these elements are greater than 1
console.log(arr.filter(x => x > 1))
// [1, 2, 3], because the function returns true for all elements
console.log(arr.filter(x => true))
// , because none of the elements equals neither 6 nor 7
console.log(arr.filter(x => x === 6 || x === 7))
const arr = [1, 2, 3]
console.log(arr.map(x => x + 1)) // [2, 3, 4]
console.log(arr.map(x => String.fromCharCode(96 + x))) // ['a', 'b', 'c']
console.log(arr.map(x => x)) // [1, 2, 3] (no-op)
console.log(arr.map(x => Math.pow(x, 2))) // [1, 4, 9]
console.log(arr.map(String)) // ['1', '2', '3']
const arr = [1, 2, 3]
console.log(arr.map(x => x + 1)) // [2, 3, 4]
console.log(arr.map(x => String.fromCharCode(96 + x))) // ['a', 'b', 'c']
console.log(arr.map(x => x)) // [1, 2, 3] (no-op)
console.log(arr.map(x => Math.pow(x, 2))) // [1, 4, 9]
console.log(arr.map(String)) // ['1', '2', '3']
const arr = [1, 2, 3]
// Sum of array elements.
console.log(arr.reduce((a, b) => a + b)) // 6
// The largest number in the array.
console.log(arr.reduce((a, b) => a > b ? a : b)) // 3
const arr = [1, 2, 3]
// Sum of array elements.
console.log(arr.reduce((a, b) => a + b)) // 6
// The largest number in the array.
console.log(arr.reduce((a, b) => a > b ? a : b)) // 3
const sum = arr => arr.reduce((a, b) => a + b, 0)
console.log(sum()) // 0
console.log(sum([4])) // 4
console.log(sum([2, 5])) // 7
const sum = arr => arr.reduce((a, b) => a + b, 0)
console.log(sum()) // 0
console.log(sum([4])) // 4
console.log(sum([2, 5])) // 7
answered Oct 22 '16 at 18:38
Michał Perłakowski
41.1k1698115
41.1k1698115
add a comment |
add a comment |
This question is quite old, so as a contemporary update. With the onset of ES2015 there are alternatives to get a hold of the data you require. There is now a feature called object destructuring for accessing nested objects.
const data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
const {
items: [, {
name: secondName
}]
} = data;
console.log(secondName);
The above example creates a variable called secondName
from the name
key from an array called items
, the lonely ,
says skip the first object in the array.
Notably it's probably overkill for this example, as simple array acccess is easier to read, but it comes in useful when breaking apart objects in general.
This is very brief intro to your specific use case, destructuring can be an unusual syntax to get used to at first. I'd recommend reading Mozilla's Destructuring Assignment documentation to learn more.
add a comment |
This question is quite old, so as a contemporary update. With the onset of ES2015 there are alternatives to get a hold of the data you require. There is now a feature called object destructuring for accessing nested objects.
const data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
const {
items: [, {
name: secondName
}]
} = data;
console.log(secondName);
The above example creates a variable called secondName
from the name
key from an array called items
, the lonely ,
says skip the first object in the array.
Notably it's probably overkill for this example, as simple array acccess is easier to read, but it comes in useful when breaking apart objects in general.
This is very brief intro to your specific use case, destructuring can be an unusual syntax to get used to at first. I'd recommend reading Mozilla's Destructuring Assignment documentation to learn more.
add a comment |
This question is quite old, so as a contemporary update. With the onset of ES2015 there are alternatives to get a hold of the data you require. There is now a feature called object destructuring for accessing nested objects.
const data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
const {
items: [, {
name: secondName
}]
} = data;
console.log(secondName);
The above example creates a variable called secondName
from the name
key from an array called items
, the lonely ,
says skip the first object in the array.
Notably it's probably overkill for this example, as simple array acccess is easier to read, but it comes in useful when breaking apart objects in general.
This is very brief intro to your specific use case, destructuring can be an unusual syntax to get used to at first. I'd recommend reading Mozilla's Destructuring Assignment documentation to learn more.
This question is quite old, so as a contemporary update. With the onset of ES2015 there are alternatives to get a hold of the data you require. There is now a feature called object destructuring for accessing nested objects.
const data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
const {
items: [, {
name: secondName
}]
} = data;
console.log(secondName);
The above example creates a variable called secondName
from the name
key from an array called items
, the lonely ,
says skip the first object in the array.
Notably it's probably overkill for this example, as simple array acccess is easier to read, but it comes in useful when breaking apart objects in general.
This is very brief intro to your specific use case, destructuring can be an unusual syntax to get used to at first. I'd recommend reading Mozilla's Destructuring Assignment documentation to learn more.
const data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
const {
items: [, {
name: secondName
}]
} = data;
console.log(secondName);
const data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
const {
items: [, {
name: secondName
}]
} = data;
console.log(secondName);
edited Aug 25 '16 at 9:32
Jon Chesterfield
1,46411322
1,46411322
answered May 6 '16 at 10:45
Alex KeySmith
10k448108
10k448108
add a comment |
add a comment |
Using JSONPath would be one of the most flexible solutions if you are willing to include a library:
https://github.com/s3u/JSONPath (node and browser)
For your use case the json path would be:
$..items[1].name
so:
var secondName = jsonPath.eval(data, "$..items[1].name");
Using eval() is not good solution. Instead first class function can be used.
– pradeep gowda
Sep 27 '17 at 12:18
add a comment |
Using JSONPath would be one of the most flexible solutions if you are willing to include a library:
https://github.com/s3u/JSONPath (node and browser)
For your use case the json path would be:
$..items[1].name
so:
var secondName = jsonPath.eval(data, "$..items[1].name");
Using eval() is not good solution. Instead first class function can be used.
– pradeep gowda
Sep 27 '17 at 12:18
add a comment |
Using JSONPath would be one of the most flexible solutions if you are willing to include a library:
https://github.com/s3u/JSONPath (node and browser)
For your use case the json path would be:
$..items[1].name
so:
var secondName = jsonPath.eval(data, "$..items[1].name");
Using JSONPath would be one of the most flexible solutions if you are willing to include a library:
https://github.com/s3u/JSONPath (node and browser)
For your use case the json path would be:
$..items[1].name
so:
var secondName = jsonPath.eval(data, "$..items[1].name");
answered Jun 26 '14 at 12:43
Andrejs
18.6k98482
18.6k98482
Using eval() is not good solution. Instead first class function can be used.
– pradeep gowda
Sep 27 '17 at 12:18
add a comment |
Using eval() is not good solution. Instead first class function can be used.
– pradeep gowda
Sep 27 '17 at 12:18
Using eval() is not good solution. Instead first class function can be used.
– pradeep gowda
Sep 27 '17 at 12:18
Using eval() is not good solution. Instead first class function can be used.
– pradeep gowda
Sep 27 '17 at 12:18
add a comment |
I prefer JQuery. It's cleaner and easy to read.
$.each($.parseJSON(data), function (key, value) {
alert(value.<propertyname>);
});
add a comment |
I prefer JQuery. It's cleaner and easy to read.
$.each($.parseJSON(data), function (key, value) {
alert(value.<propertyname>);
});
add a comment |
I prefer JQuery. It's cleaner and easy to read.
$.each($.parseJSON(data), function (key, value) {
alert(value.<propertyname>);
});
I prefer JQuery. It's cleaner and easy to read.
$.each($.parseJSON(data), function (key, value) {
alert(value.<propertyname>);
});
$.each($.parseJSON(data), function (key, value) {
alert(value.<propertyname>);
});
$.each($.parseJSON(data), function (key, value) {
alert(value.<propertyname>);
});
answered Feb 24 '16 at 15:55
Rudy Hinojosa
815912
815912
add a comment |
add a comment |
You could use lodash _get
function:
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.get(object, 'a[0].b.c');
// => 3
add a comment |
You could use lodash _get
function:
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.get(object, 'a[0].b.c');
// => 3
add a comment |
You could use lodash _get
function:
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.get(object, 'a[0].b.c');
// => 3
You could use lodash _get
function:
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.get(object, 'a[0].b.c');
// => 3
edited Jul 3 '17 at 4:24
Koby Douek
11.5k133659
11.5k133659
answered Jul 2 '17 at 19:08
Sergey
984
984
add a comment |
add a comment |
To access a nested attribute, you need to specify its name and then search through the object.
If you already know the exact path, then you can hardcode it in your script like so:
data['items'][1]['name']
these also work -
data.items[1].name
data['items'][1].name
data.items[1]['name']
When you don't know the exact name before hand, or a user is the one who provides the name for you. Then dynamically searching through the data structure is required. Some suggested here that the search can be done using a for
loop, but there is a very simple way to traverse a path using Array.reduce
.
const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] }
const path = [ 'items', '1', 'name']
let result = path.reduce((a,v) => a[v], data)
The path is a way to say: First take the object with key items
, which happens to be an array. Then take the 1
-st element (0 index arrays). Last take the object with key name
in that array element, which happens to be the string bar
.
If you have a very long path, you might even use String.split
to make all of this easier -
'items.1.name'.split('.').reduce((a,v) => a[v], data)
This is just plain JavaScript, without using any third party libraries like jQuery or lodash.
add a comment |
To access a nested attribute, you need to specify its name and then search through the object.
If you already know the exact path, then you can hardcode it in your script like so:
data['items'][1]['name']
these also work -
data.items[1].name
data['items'][1].name
data.items[1]['name']
When you don't know the exact name before hand, or a user is the one who provides the name for you. Then dynamically searching through the data structure is required. Some suggested here that the search can be done using a for
loop, but there is a very simple way to traverse a path using Array.reduce
.
const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] }
const path = [ 'items', '1', 'name']
let result = path.reduce((a,v) => a[v], data)
The path is a way to say: First take the object with key items
, which happens to be an array. Then take the 1
-st element (0 index arrays). Last take the object with key name
in that array element, which happens to be the string bar
.
If you have a very long path, you might even use String.split
to make all of this easier -
'items.1.name'.split('.').reduce((a,v) => a[v], data)
This is just plain JavaScript, without using any third party libraries like jQuery or lodash.
add a comment |
To access a nested attribute, you need to specify its name and then search through the object.
If you already know the exact path, then you can hardcode it in your script like so:
data['items'][1]['name']
these also work -
data.items[1].name
data['items'][1].name
data.items[1]['name']
When you don't know the exact name before hand, or a user is the one who provides the name for you. Then dynamically searching through the data structure is required. Some suggested here that the search can be done using a for
loop, but there is a very simple way to traverse a path using Array.reduce
.
const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] }
const path = [ 'items', '1', 'name']
let result = path.reduce((a,v) => a[v], data)
The path is a way to say: First take the object with key items
, which happens to be an array. Then take the 1
-st element (0 index arrays). Last take the object with key name
in that array element, which happens to be the string bar
.
If you have a very long path, you might even use String.split
to make all of this easier -
'items.1.name'.split('.').reduce((a,v) => a[v], data)
This is just plain JavaScript, without using any third party libraries like jQuery or lodash.
To access a nested attribute, you need to specify its name and then search through the object.
If you already know the exact path, then you can hardcode it in your script like so:
data['items'][1]['name']
these also work -
data.items[1].name
data['items'][1].name
data.items[1]['name']
When you don't know the exact name before hand, or a user is the one who provides the name for you. Then dynamically searching through the data structure is required. Some suggested here that the search can be done using a for
loop, but there is a very simple way to traverse a path using Array.reduce
.
const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] }
const path = [ 'items', '1', 'name']
let result = path.reduce((a,v) => a[v], data)
The path is a way to say: First take the object with key items
, which happens to be an array. Then take the 1
-st element (0 index arrays). Last take the object with key name
in that array element, which happens to be the string bar
.
If you have a very long path, you might even use String.split
to make all of this easier -
'items.1.name'.split('.').reduce((a,v) => a[v], data)
This is just plain JavaScript, without using any third party libraries like jQuery or lodash.
edited Feb 15 at 10:17
answered Feb 15 at 10:06
Evgeny
3,22213850
3,22213850
add a comment |
add a comment |
If you are looking for one or more objects that meets certain criteria you have a few options using query-js
//will return all elements with an id larger than 1
data.items.where(function(e){return e.id > 1;});
//will return the first element with an id larger than 1
data.items.first(function(e){return e.id > 1;});
//will return the first element with an id larger than 1
//or the second argument if non are found
data.items.first(function(e){return e.id > 1;},{id:-1,name:""});
There's also a single
and a singleOrDefault
they work much like first
and firstOrDefault
respectively. The only difference is that they will throw if more than one match is found.
for further explanation of query-js you can start with this post
I would love to know how this could be improved. Care to leave a comment?
– Rune FS
Jun 18 '15 at 18:42
add a comment |
If you are looking for one or more objects that meets certain criteria you have a few options using query-js
//will return all elements with an id larger than 1
data.items.where(function(e){return e.id > 1;});
//will return the first element with an id larger than 1
data.items.first(function(e){return e.id > 1;});
//will return the first element with an id larger than 1
//or the second argument if non are found
data.items.first(function(e){return e.id > 1;},{id:-1,name:""});
There's also a single
and a singleOrDefault
they work much like first
and firstOrDefault
respectively. The only difference is that they will throw if more than one match is found.
for further explanation of query-js you can start with this post
I would love to know how this could be improved. Care to leave a comment?
– Rune FS
Jun 18 '15 at 18:42
add a comment |
If you are looking for one or more objects that meets certain criteria you have a few options using query-js
//will return all elements with an id larger than 1
data.items.where(function(e){return e.id > 1;});
//will return the first element with an id larger than 1
data.items.first(function(e){return e.id > 1;});
//will return the first element with an id larger than 1
//or the second argument if non are found
data.items.first(function(e){return e.id > 1;},{id:-1,name:""});
There's also a single
and a singleOrDefault
they work much like first
and firstOrDefault
respectively. The only difference is that they will throw if more than one match is found.
for further explanation of query-js you can start with this post
If you are looking for one or more objects that meets certain criteria you have a few options using query-js
//will return all elements with an id larger than 1
data.items.where(function(e){return e.id > 1;});
//will return the first element with an id larger than 1
data.items.first(function(e){return e.id > 1;});
//will return the first element with an id larger than 1
//or the second argument if non are found
data.items.first(function(e){return e.id > 1;},{id:-1,name:""});
There's also a single
and a singleOrDefault
they work much like first
and firstOrDefault
respectively. The only difference is that they will throw if more than one match is found.
for further explanation of query-js you can start with this post
edited Jun 18 '15 at 8:35
Bergi
362k57538862
362k57538862
answered Jun 17 '15 at 12:16
Rune FS
18.3k64787
18.3k64787
I would love to know how this could be improved. Care to leave a comment?
– Rune FS
Jun 18 '15 at 18:42
add a comment |
I would love to know how this could be improved. Care to leave a comment?
– Rune FS
Jun 18 '15 at 18:42
I would love to know how this could be improved. Care to leave a comment?
– Rune FS
Jun 18 '15 at 18:42
I would love to know how this could be improved. Care to leave a comment?
– Rune FS
Jun 18 '15 at 18:42
add a comment |
The Underscore js Way
Which is a JavaScript library that provides a whole mess of useful functional programming
helpers without extending any built-in objects.
Solution:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
var item = _.findWhere(data.items, {
id: 2
});
if (!_.isUndefined(item)) {
console.log('NAME =>', item.name);
}
//using find -
var item = _.find(data.items, function(item) {
return item.id === 2;
});
if (!_.isUndefined(item)) {
console.log('NAME =>', item.name);
}
add a comment |
The Underscore js Way
Which is a JavaScript library that provides a whole mess of useful functional programming
helpers without extending any built-in objects.
Solution:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
var item = _.findWhere(data.items, {
id: 2
});
if (!_.isUndefined(item)) {
console.log('NAME =>', item.name);
}
//using find -
var item = _.find(data.items, function(item) {
return item.id === 2;
});
if (!_.isUndefined(item)) {
console.log('NAME =>', item.name);
}
add a comment |
The Underscore js Way
Which is a JavaScript library that provides a whole mess of useful functional programming
helpers without extending any built-in objects.
Solution:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
var item = _.findWhere(data.items, {
id: 2
});
if (!_.isUndefined(item)) {
console.log('NAME =>', item.name);
}
//using find -
var item = _.find(data.items, function(item) {
return item.id === 2;
});
if (!_.isUndefined(item)) {
console.log('NAME =>', item.name);
}
The Underscore js Way
Which is a JavaScript library that provides a whole mess of useful functional programming
helpers without extending any built-in objects.
Solution:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
var item = _.findWhere(data.items, {
id: 2
});
if (!_.isUndefined(item)) {
console.log('NAME =>', item.name);
}
//using find -
var item = _.find(data.items, function(item) {
return item.id === 2;
});
if (!_.isUndefined(item)) {
console.log('NAME =>', item.name);
}
edited Aug 13 '16 at 10:50
answered Aug 13 '16 at 10:39
Mohan Dere
2,41411013
2,41411013
add a comment |
add a comment |
Accessing dynamically multi levels object.
var obj = {
name: "salut",
subobj: {
subsubobj: {
names: "I am sub sub obj"
}
}
};
var level = "subobj.subsubobj.names";
level = level.split(".");
var currentObjState = obj;
for (var i = 0; i < level.length; i++) {
currentObjState = currentObjState[level[i]];
}
console.log(currentObjState);
Working fiddle: https://jsfiddle.net/andreitodorut/3mws3kjL/
add a comment |
Accessing dynamically multi levels object.
var obj = {
name: "salut",
subobj: {
subsubobj: {
names: "I am sub sub obj"
}
}
};
var level = "subobj.subsubobj.names";
level = level.split(".");
var currentObjState = obj;
for (var i = 0; i < level.length; i++) {
currentObjState = currentObjState[level[i]];
}
console.log(currentObjState);
Working fiddle: https://jsfiddle.net/andreitodorut/3mws3kjL/
add a comment |
Accessing dynamically multi levels object.
var obj = {
name: "salut",
subobj: {
subsubobj: {
names: "I am sub sub obj"
}
}
};
var level = "subobj.subsubobj.names";
level = level.split(".");
var currentObjState = obj;
for (var i = 0; i < level.length; i++) {
currentObjState = currentObjState[level[i]];
}
console.log(currentObjState);
Working fiddle: https://jsfiddle.net/andreitodorut/3mws3kjL/
Accessing dynamically multi levels object.
var obj = {
name: "salut",
subobj: {
subsubobj: {
names: "I am sub sub obj"
}
}
};
var level = "subobj.subsubobj.names";
level = level.split(".");
var currentObjState = obj;
for (var i = 0; i < level.length; i++) {
currentObjState = currentObjState[level[i]];
}
console.log(currentObjState);
Working fiddle: https://jsfiddle.net/andreitodorut/3mws3kjL/
edited Mar 27 at 20:39
Ilyas karim
1,17411625
1,17411625
answered Jan 25 at 10:24
Andrei Todorut
2,0741614
2,0741614
add a comment |
add a comment |
I don't think questioner just only concern one level nested object, so I present the following demo to demonstrate how to access the node of deeply nested json object. All right, let's find the node with id '5'.
var data = {
code: 42,
items: [{
id: 1,
name: 'aaa',
items: [{
id: 3,
name: 'ccc'
}, {
id: 4,
name: 'ddd'
}]
}, {
id: 2,
name: 'bbb',
items: [{
id: 5,
name: 'eee'
}, {
id: 6,
name: 'fff'
}]
}]
};
var jsonloop = new JSONLoop(data, 'id', 'items');
jsonloop.findNodeById(data, 5, function(err, node) {
if (err) {
document.write(err);
} else {
document.write(JSON.stringify(node, null, 2));
}
});
<script src="https://rawgit.com/dabeng/JSON-Loop/master/JSONLoop.js"></script>
How do I access nested json object using variables. data = {a: {b:'ss'}}; var key = a.b data[key] not working
– Pasupathi Rajamanickam
Nov 14 '17 at 20:51
add a comment |
I don't think questioner just only concern one level nested object, so I present the following demo to demonstrate how to access the node of deeply nested json object. All right, let's find the node with id '5'.
var data = {
code: 42,
items: [{
id: 1,
name: 'aaa',
items: [{
id: 3,
name: 'ccc'
}, {
id: 4,
name: 'ddd'
}]
}, {
id: 2,
name: 'bbb',
items: [{
id: 5,
name: 'eee'
}, {
id: 6,
name: 'fff'
}]
}]
};
var jsonloop = new JSONLoop(data, 'id', 'items');
jsonloop.findNodeById(data, 5, function(err, node) {
if (err) {
document.write(err);
} else {
document.write(JSON.stringify(node, null, 2));
}
});
<script src="https://rawgit.com/dabeng/JSON-Loop/master/JSONLoop.js"></script>
How do I access nested json object using variables. data = {a: {b:'ss'}}; var key = a.b data[key] not working
– Pasupathi Rajamanickam
Nov 14 '17 at 20:51
add a comment |
I don't think questioner just only concern one level nested object, so I present the following demo to demonstrate how to access the node of deeply nested json object. All right, let's find the node with id '5'.
var data = {
code: 42,
items: [{
id: 1,
name: 'aaa',
items: [{
id: 3,
name: 'ccc'
}, {
id: 4,
name: 'ddd'
}]
}, {
id: 2,
name: 'bbb',
items: [{
id: 5,
name: 'eee'
}, {
id: 6,
name: 'fff'
}]
}]
};
var jsonloop = new JSONLoop(data, 'id', 'items');
jsonloop.findNodeById(data, 5, function(err, node) {
if (err) {
document.write(err);
} else {
document.write(JSON.stringify(node, null, 2));
}
});
<script src="https://rawgit.com/dabeng/JSON-Loop/master/JSONLoop.js"></script>
I don't think questioner just only concern one level nested object, so I present the following demo to demonstrate how to access the node of deeply nested json object. All right, let's find the node with id '5'.
var data = {
code: 42,
items: [{
id: 1,
name: 'aaa',
items: [{
id: 3,
name: 'ccc'
}, {
id: 4,
name: 'ddd'
}]
}, {
id: 2,
name: 'bbb',
items: [{
id: 5,
name: 'eee'
}, {
id: 6,
name: 'fff'
}]
}]
};
var jsonloop = new JSONLoop(data, 'id', 'items');
jsonloop.findNodeById(data, 5, function(err, node) {
if (err) {
document.write(err);
} else {
document.write(JSON.stringify(node, null, 2));
}
});
<script src="https://rawgit.com/dabeng/JSON-Loop/master/JSONLoop.js"></script>
var data = {
code: 42,
items: [{
id: 1,
name: 'aaa',
items: [{
id: 3,
name: 'ccc'
}, {
id: 4,
name: 'ddd'
}]
}, {
id: 2,
name: 'bbb',
items: [{
id: 5,
name: 'eee'
}, {
id: 6,
name: 'fff'
}]
}]
};
var jsonloop = new JSONLoop(data, 'id', 'items');
jsonloop.findNodeById(data, 5, function(err, node) {
if (err) {
document.write(err);
} else {
document.write(JSON.stringify(node, null, 2));
}
});
<script src="https://rawgit.com/dabeng/JSON-Loop/master/JSONLoop.js"></script>
var data = {
code: 42,
items: [{
id: 1,
name: 'aaa',
items: [{
id: 3,
name: 'ccc'
}, {
id: 4,
name: 'ddd'
}]
}, {
id: 2,
name: 'bbb',
items: [{
id: 5,
name: 'eee'
}, {
id: 6,
name: 'fff'
}]
}]
};
var jsonloop = new JSONLoop(data, 'id', 'items');
jsonloop.findNodeById(data, 5, function(err, node) {
if (err) {
document.write(err);
} else {
document.write(JSON.stringify(node, null, 2));
}
});
<script src="https://rawgit.com/dabeng/JSON-Loop/master/JSONLoop.js"></script>
answered Feb 22 '17 at 9:00
dabeng
13415
13415
How do I access nested json object using variables. data = {a: {b:'ss'}}; var key = a.b data[key] not working
– Pasupathi Rajamanickam
Nov 14 '17 at 20:51
add a comment |
How do I access nested json object using variables. data = {a: {b:'ss'}}; var key = a.b data[key] not working
– Pasupathi Rajamanickam
Nov 14 '17 at 20:51
How do I access nested json object using variables. data = {a: {b:'ss'}}; var key = a.b data[key] not working
– Pasupathi Rajamanickam
Nov 14 '17 at 20:51
How do I access nested json object using variables. data = {a: {b:'ss'}}; var key = a.b data[key] not working
– Pasupathi Rajamanickam
Nov 14 '17 at 20:51
add a comment |
Old question but as nobody mentioned lodash (just underscore).
In case you are already using lodash in your project, I think an elegant way to do this in a complex example:
Opt 1
_.get(response, ['output', 'fund', 'data', '0', 'children', '0', 'group', 'myValue'], '')
same as:
Opt 2
response.output.fund.data[0].children[0].group.myValue
The difference between the first and second option is that in the Opt 1 if you have one of the properties missing (undefined) in the path you don't get an error, it returns you the third parameter.
For array filter lodash has _.find()
but I'd rather use the regular filter()
. But I still think the above method _.get()
is super useful when working with really complex data. I faced in the past really complex APIs and it was handy!
I hope it can be useful for who's looking for options to manipulate really complex data which the title implies.
add a comment |
Old question but as nobody mentioned lodash (just underscore).
In case you are already using lodash in your project, I think an elegant way to do this in a complex example:
Opt 1
_.get(response, ['output', 'fund', 'data', '0', 'children', '0', 'group', 'myValue'], '')
same as:
Opt 2
response.output.fund.data[0].children[0].group.myValue
The difference between the first and second option is that in the Opt 1 if you have one of the properties missing (undefined) in the path you don't get an error, it returns you the third parameter.
For array filter lodash has _.find()
but I'd rather use the regular filter()
. But I still think the above method _.get()
is super useful when working with really complex data. I faced in the past really complex APIs and it was handy!
I hope it can be useful for who's looking for options to manipulate really complex data which the title implies.
add a comment |
Old question but as nobody mentioned lodash (just underscore).
In case you are already using lodash in your project, I think an elegant way to do this in a complex example:
Opt 1
_.get(response, ['output', 'fund', 'data', '0', 'children', '0', 'group', 'myValue'], '')
same as:
Opt 2
response.output.fund.data[0].children[0].group.myValue
The difference between the first and second option is that in the Opt 1 if you have one of the properties missing (undefined) in the path you don't get an error, it returns you the third parameter.
For array filter lodash has _.find()
but I'd rather use the regular filter()
. But I still think the above method _.get()
is super useful when working with really complex data. I faced in the past really complex APIs and it was handy!
I hope it can be useful for who's looking for options to manipulate really complex data which the title implies.
Old question but as nobody mentioned lodash (just underscore).
In case you are already using lodash in your project, I think an elegant way to do this in a complex example:
Opt 1
_.get(response, ['output', 'fund', 'data', '0', 'children', '0', 'group', 'myValue'], '')
same as:
Opt 2
response.output.fund.data[0].children[0].group.myValue
The difference between the first and second option is that in the Opt 1 if you have one of the properties missing (undefined) in the path you don't get an error, it returns you the third parameter.
For array filter lodash has _.find()
but I'd rather use the regular filter()
. But I still think the above method _.get()
is super useful when working with really complex data. I faced in the past really complex APIs and it was handy!
I hope it can be useful for who's looking for options to manipulate really complex data which the title implies.
answered Jul 1 '17 at 11:46
Ventura
1,2721632
1,2721632
add a comment |
add a comment |
var ourStorage = {
"desk": {
"drawer": "stapler"
},
"cabinet": {
"top drawer": {
"folder1": "a file",
"folder2": "secrets"
},
"bottom drawer": "soda"
}
};
ourStorage.cabinet["top drawer"].folder2; // Outputs -> "secrets"
or
//parent.subParent.subsubParent["almost there"]["final property"]
Basically, use a dot between each descendant that unfolds underneath it and when you have object names made out of two strings, you must use the ["obj Name"] notation. Otherwise, just a dot would suffice;
Source: https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-objects
to add to this, accessing nested Arrays would happen like so:
var ourPets = [
{
animalType: "cat",
names: [
"Meowzer",
"Fluffy",
"Kit-Cat"
]
},
{
animalType: "dog",
names: [
"Spot",
"Bowser",
"Frankie"
]
}
];
ourPets[0].names[1]; // Outputs "Fluffy"
ourPets[1].names[0]; // Outputs "Spot"
Source: https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-arrays/
While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review
– Robert
Aug 19 at 23:33
I edited the post. Allthough people were quick to give bad rep to it. Next time I'll refrain from giving an answer.
– Riddick
Aug 20 at 0:04
@Riddick don't refrain, just make sure you don't post only a link
– reggaeguitar
Sep 27 at 18:02
add a comment |
var ourStorage = {
"desk": {
"drawer": "stapler"
},
"cabinet": {
"top drawer": {
"folder1": "a file",
"folder2": "secrets"
},
"bottom drawer": "soda"
}
};
ourStorage.cabinet["top drawer"].folder2; // Outputs -> "secrets"
or
//parent.subParent.subsubParent["almost there"]["final property"]
Basically, use a dot between each descendant that unfolds underneath it and when you have object names made out of two strings, you must use the ["obj Name"] notation. Otherwise, just a dot would suffice;
Source: https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-objects
to add to this, accessing nested Arrays would happen like so:
var ourPets = [
{
animalType: "cat",
names: [
"Meowzer",
"Fluffy",
"Kit-Cat"
]
},
{
animalType: "dog",
names: [
"Spot",
"Bowser",
"Frankie"
]
}
];
ourPets[0].names[1]; // Outputs "Fluffy"
ourPets[1].names[0]; // Outputs "Spot"
Source: https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-arrays/
While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review
– Robert
Aug 19 at 23:33
I edited the post. Allthough people were quick to give bad rep to it. Next time I'll refrain from giving an answer.
– Riddick
Aug 20 at 0:04
@Riddick don't refrain, just make sure you don't post only a link
– reggaeguitar
Sep 27 at 18:02
add a comment |
var ourStorage = {
"desk": {
"drawer": "stapler"
},
"cabinet": {
"top drawer": {
"folder1": "a file",
"folder2": "secrets"
},
"bottom drawer": "soda"
}
};
ourStorage.cabinet["top drawer"].folder2; // Outputs -> "secrets"
or
//parent.subParent.subsubParent["almost there"]["final property"]
Basically, use a dot between each descendant that unfolds underneath it and when you have object names made out of two strings, you must use the ["obj Name"] notation. Otherwise, just a dot would suffice;
Source: https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-objects
to add to this, accessing nested Arrays would happen like so:
var ourPets = [
{
animalType: "cat",
names: [
"Meowzer",
"Fluffy",
"Kit-Cat"
]
},
{
animalType: "dog",
names: [
"Spot",
"Bowser",
"Frankie"
]
}
];
ourPets[0].names[1]; // Outputs "Fluffy"
ourPets[1].names[0]; // Outputs "Spot"
Source: https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-arrays/
var ourStorage = {
"desk": {
"drawer": "stapler"
},
"cabinet": {
"top drawer": {
"folder1": "a file",
"folder2": "secrets"
},
"bottom drawer": "soda"
}
};
ourStorage.cabinet["top drawer"].folder2; // Outputs -> "secrets"
or
//parent.subParent.subsubParent["almost there"]["final property"]
Basically, use a dot between each descendant that unfolds underneath it and when you have object names made out of two strings, you must use the ["obj Name"] notation. Otherwise, just a dot would suffice;
Source: https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-objects
to add to this, accessing nested Arrays would happen like so:
var ourPets = [
{
animalType: "cat",
names: [
"Meowzer",
"Fluffy",
"Kit-Cat"
]
},
{
animalType: "dog",
names: [
"Spot",
"Bowser",
"Frankie"
]
}
];
ourPets[0].names[1]; // Outputs "Fluffy"
ourPets[1].names[0]; // Outputs "Spot"
Source: https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-arrays/
edited Aug 19 at 23:53
answered Aug 19 at 23:01
Riddick
70110
70110
While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review
– Robert
Aug 19 at 23:33
I edited the post. Allthough people were quick to give bad rep to it. Next time I'll refrain from giving an answer.
– Riddick
Aug 20 at 0:04
@Riddick don't refrain, just make sure you don't post only a link
– reggaeguitar
Sep 27 at 18:02
add a comment |
While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review
– Robert
Aug 19 at 23:33
I edited the post. Allthough people were quick to give bad rep to it. Next time I'll refrain from giving an answer.
– Riddick
Aug 20 at 0:04
@Riddick don't refrain, just make sure you don't post only a link
– reggaeguitar
Sep 27 at 18:02
While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review
– Robert
Aug 19 at 23:33
While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review
– Robert
Aug 19 at 23:33
I edited the post. Allthough people were quick to give bad rep to it. Next time I'll refrain from giving an answer.
– Riddick
Aug 20 at 0:04
I edited the post. Allthough people were quick to give bad rep to it. Next time I'll refrain from giving an answer.
– Riddick
Aug 20 at 0:04
@Riddick don't refrain, just make sure you don't post only a link
– reggaeguitar
Sep 27 at 18:02
@Riddick don't refrain, just make sure you don't post only a link
– reggaeguitar
Sep 27 at 18:02
add a comment |
A pythonic, recursive and functional approach to unravel arbitrary JSON trees:
handlers = {
list: iterate,
dict: delve,
str: emit_li,
float: emit_li,
}
def emit_li(stuff, strong=False):
emission = '<li><strong>%s</strong></li>' if strong else '<li>%s</li>'
print(emission % stuff)
def iterate(a_list):
print('<ul>')
map(unravel, a_list)
print('</ul>')
def delve(a_dict):
print('<ul>')
for key, value in a_dict.items():
emit_li(key, strong=True)
unravel(value)
print('</ul>')
def unravel(structure):
h = handlers[type(structure)]
return h(structure)
unravel(data)
where data is a python list (parsed from a JSON text string):
data = [
{'data': {'customKey1': 'customValue1',
'customKey2': {'customSubKey1': {'customSubSubKey1': 'keyvalue'}}},
'geometry': {'location': {'lat': 37.3860517, 'lng': -122.0838511},
'viewport': {'northeast': {'lat': 37.4508789,
'lng': -122.0446721},
'southwest': {'lat': 37.3567599,
'lng': -122.1178619}}},
'name': 'Mountain View',
'scope': 'GOOGLE',
'types': ['locality', 'political']}
]
2
This question is about JavaScript, not Python. Not sure whether there is an equivalent question for Python.
– Felix Kling
Dec 28 '16 at 19:54
Lo, thanks for your Python answer on JavaScript Question
– Ilyas karim
Mar 27 at 19:46
Tough crowd, here.
– pX0r
Jul 19 at 7:05
add a comment |
A pythonic, recursive and functional approach to unravel arbitrary JSON trees:
handlers = {
list: iterate,
dict: delve,
str: emit_li,
float: emit_li,
}
def emit_li(stuff, strong=False):
emission = '<li><strong>%s</strong></li>' if strong else '<li>%s</li>'
print(emission % stuff)
def iterate(a_list):
print('<ul>')
map(unravel, a_list)
print('</ul>')
def delve(a_dict):
print('<ul>')
for key, value in a_dict.items():
emit_li(key, strong=True)
unravel(value)
print('</ul>')
def unravel(structure):
h = handlers[type(structure)]
return h(structure)
unravel(data)
where data is a python list (parsed from a JSON text string):
data = [
{'data': {'customKey1': 'customValue1',
'customKey2': {'customSubKey1': {'customSubSubKey1': 'keyvalue'}}},
'geometry': {'location': {'lat': 37.3860517, 'lng': -122.0838511},
'viewport': {'northeast': {'lat': 37.4508789,
'lng': -122.0446721},
'southwest': {'lat': 37.3567599,
'lng': -122.1178619}}},
'name': 'Mountain View',
'scope': 'GOOGLE',
'types': ['locality', 'political']}
]
2
This question is about JavaScript, not Python. Not sure whether there is an equivalent question for Python.
– Felix Kling
Dec 28 '16 at 19:54
Lo, thanks for your Python answer on JavaScript Question
– Ilyas karim
Mar 27 at 19:46
Tough crowd, here.
– pX0r
Jul 19 at 7:05
add a comment |
A pythonic, recursive and functional approach to unravel arbitrary JSON trees:
handlers = {
list: iterate,
dict: delve,
str: emit_li,
float: emit_li,
}
def emit_li(stuff, strong=False):
emission = '<li><strong>%s</strong></li>' if strong else '<li>%s</li>'
print(emission % stuff)
def iterate(a_list):
print('<ul>')
map(unravel, a_list)
print('</ul>')
def delve(a_dict):
print('<ul>')
for key, value in a_dict.items():
emit_li(key, strong=True)
unravel(value)
print('</ul>')
def unravel(structure):
h = handlers[type(structure)]
return h(structure)
unravel(data)
where data is a python list (parsed from a JSON text string):
data = [
{'data': {'customKey1': 'customValue1',
'customKey2': {'customSubKey1': {'customSubSubKey1': 'keyvalue'}}},
'geometry': {'location': {'lat': 37.3860517, 'lng': -122.0838511},
'viewport': {'northeast': {'lat': 37.4508789,
'lng': -122.0446721},
'southwest': {'lat': 37.3567599,
'lng': -122.1178619}}},
'name': 'Mountain View',
'scope': 'GOOGLE',
'types': ['locality', 'political']}
]
A pythonic, recursive and functional approach to unravel arbitrary JSON trees:
handlers = {
list: iterate,
dict: delve,
str: emit_li,
float: emit_li,
}
def emit_li(stuff, strong=False):
emission = '<li><strong>%s</strong></li>' if strong else '<li>%s</li>'
print(emission % stuff)
def iterate(a_list):
print('<ul>')
map(unravel, a_list)
print('</ul>')
def delve(a_dict):
print('<ul>')
for key, value in a_dict.items():
emit_li(key, strong=True)
unravel(value)
print('</ul>')
def unravel(structure):
h = handlers[type(structure)]
return h(structure)
unravel(data)
where data is a python list (parsed from a JSON text string):
data = [
{'data': {'customKey1': 'customValue1',
'customKey2': {'customSubKey1': {'customSubSubKey1': 'keyvalue'}}},
'geometry': {'location': {'lat': 37.3860517, 'lng': -122.0838511},
'viewport': {'northeast': {'lat': 37.4508789,
'lng': -122.0446721},
'southwest': {'lat': 37.3567599,
'lng': -122.1178619}}},
'name': 'Mountain View',
'scope': 'GOOGLE',
'types': ['locality', 'political']}
]
edited Dec 29 '16 at 7:55
answered Dec 28 '16 at 19:53
pX0r
60369
60369
2
This question is about JavaScript, not Python. Not sure whether there is an equivalent question for Python.
– Felix Kling
Dec 28 '16 at 19:54
Lo, thanks for your Python answer on JavaScript Question
– Ilyas karim
Mar 27 at 19:46
Tough crowd, here.
– pX0r
Jul 19 at 7:05
add a comment |
2
This question is about JavaScript, not Python. Not sure whether there is an equivalent question for Python.
– Felix Kling
Dec 28 '16 at 19:54
Lo, thanks for your Python answer on JavaScript Question
– Ilyas karim
Mar 27 at 19:46
Tough crowd, here.
– pX0r
Jul 19 at 7:05
2
2
This question is about JavaScript, not Python. Not sure whether there is an equivalent question for Python.
– Felix Kling
Dec 28 '16 at 19:54
This question is about JavaScript, not Python. Not sure whether there is an equivalent question for Python.
– Felix Kling
Dec 28 '16 at 19:54
Lo, thanks for your Python answer on JavaScript Question
– Ilyas karim
Mar 27 at 19:46
Lo, thanks for your Python answer on JavaScript Question
– Ilyas karim
Mar 27 at 19:46
Tough crowd, here.
– pX0r
Jul 19 at 7:05
Tough crowd, here.
– pX0r
Jul 19 at 7:05
add a comment |
jQuery's grep function lets you filter through an array:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
$.grep(data.items, function(item) {
if (item.id === 2) {
console.log(item.id); //console id of item
console.log(item.name); //console name of item
console.log(item); //console item object
return item; //returns item object
}
});
// Object {id: 2, name: "bar"}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
add a comment |
jQuery's grep function lets you filter through an array:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
$.grep(data.items, function(item) {
if (item.id === 2) {
console.log(item.id); //console id of item
console.log(item.name); //console name of item
console.log(item); //console item object
return item; //returns item object
}
});
// Object {id: 2, name: "bar"}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
add a comment |
jQuery's grep function lets you filter through an array:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
$.grep(data.items, function(item) {
if (item.id === 2) {
console.log(item.id); //console id of item
console.log(item.name); //console name of item
console.log(item); //console item object
return item; //returns item object
}
});
// Object {id: 2, name: "bar"}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
jQuery's grep function lets you filter through an array:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
$.grep(data.items, function(item) {
if (item.id === 2) {
console.log(item.id); //console id of item
console.log(item.name); //console name of item
console.log(item); //console item object
return item; //returns item object
}
});
// Object {id: 2, name: "bar"}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
$.grep(data.items, function(item) {
if (item.id === 2) {
console.log(item.id); //console id of item
console.log(item.name); //console name of item
console.log(item); //console item object
return item; //returns item object
}
});
// Object {id: 2, name: "bar"}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
$.grep(data.items, function(item) {
if (item.id === 2) {
console.log(item.id); //console id of item
console.log(item.name); //console name of item
console.log(item); //console item object
return item; //returns item object
}
});
// Object {id: 2, name: "bar"}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
answered Aug 28 '17 at 11:25
user7110739
add a comment |
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
1. Oliver Steele's nested object access pattern
The easiest and the cleanest way is to use Oliver Steele's nested object access pattern
const name = ((user || {}).personalInfo || {}).name;
With this notation, you'll never run into
Cannot read property 'name' of undefined.
You basically check if user exists, if not, you create an empty object on the fly. This way, the next level key will always be accessed from an object that exists or an empty object, but never from undefined.
2. Access Nested Objects Using Array Reduce
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', 'addresses', 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.
This question is primarily about access properties that exist. There is already a question about what you are referring to (and already including most of your solutions): Access Javascript nested objects safely or Accessing nested JavaScript objects with string key. But anyway: "Unfortunately, you cannot access nested arrays with this trick." Why not? Arrays are objects, so it should work just as well. Can you provide an example where it does not?
– Felix Kling
Jul 7 at 15:47
@FelixKling When we try to access arrays with Oliver Steele pattern, we won't be able to create array on 'n' length on the fly and access nth index without getting 'undefined' error. Ex.((user || {}).address || new Array(3))[1].name
– Dinesh Pandiyan
Jul 8 at 16:20
1
You are not applying your pattern consistently. Of course...[1].bar
would result in an error if the element1
didn't exist. But that's also the case for....foo.bar
iffoo
didn't exist. You have to "guard" accessing1
as well, just like you "guard" any other property access. An array is just an object. An "array element" is just a property. Correctly applied it would be(((user || {}).address || {})[1] || {}).name
.
– Felix Kling
Jul 9 at 3:49
This is great. It didn't strike me this way. Thank @FelixKling, I'll go update the blog posts.
– Dinesh Pandiyan
Jul 9 at 4:01
@DineshPandiyan you should disclose that you're the author of typy, I just came here after reading your blog post
– reggaeguitar
Sep 27 at 18:03
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
1. Oliver Steele's nested object access pattern
The easiest and the cleanest way is to use Oliver Steele's nested object access pattern
const name = ((user || {}).personalInfo || {}).name;
With this notation, you'll never run into
Cannot read property 'name' of undefined.
You basically check if user exists, if not, you create an empty object on the fly. This way, the next level key will always be accessed from an object that exists or an empty object, but never from undefined.
2. Access Nested Objects Using Array Reduce
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', 'addresses', 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.
This question is primarily about access properties that exist. There is already a question about what you are referring to (and already including most of your solutions): Access Javascript nested objects safely or Accessing nested JavaScript objects with string key. But anyway: "Unfortunately, you cannot access nested arrays with this trick." Why not? Arrays are objects, so it should work just as well. Can you provide an example where it does not?
– Felix Kling
Jul 7 at 15:47
@FelixKling When we try to access arrays with Oliver Steele pattern, we won't be able to create array on 'n' length on the fly and access nth index without getting 'undefined' error. Ex.((user || {}).address || new Array(3))[1].name
– Dinesh Pandiyan
Jul 8 at 16:20
1
You are not applying your pattern consistently. Of course...[1].bar
would result in an error if the element1
didn't exist. But that's also the case for....foo.bar
iffoo
didn't exist. You have to "guard" accessing1
as well, just like you "guard" any other property access. An array is just an object. An "array element" is just a property. Correctly applied it would be(((user || {}).address || {})[1] || {}).name
.
– Felix Kling
Jul 9 at 3:49
This is great. It didn't strike me this way. Thank @FelixKling, I'll go update the blog posts.
– Dinesh Pandiyan
Jul 9 at 4:01
@DineshPandiyan you should disclose that you're the author of typy, I just came here after reading your blog post
– reggaeguitar
Sep 27 at 18:03
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
1. Oliver Steele's nested object access pattern
The easiest and the cleanest way is to use Oliver Steele's nested object access pattern
const name = ((user || {}).personalInfo || {}).name;
With this notation, you'll never run into
Cannot read property 'name' of undefined.
You basically check if user exists, if not, you create an empty object on the fly. This way, the next level key will always be accessed from an object that exists or an empty object, but never from undefined.
2. Access Nested Objects Using Array Reduce
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', 'addresses', 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.
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
1. Oliver Steele's nested object access pattern
The easiest and the cleanest way is to use Oliver Steele's nested object access pattern
const name = ((user || {}).personalInfo || {}).name;
With this notation, you'll never run into
Cannot read property 'name' of undefined.
You basically check if user exists, if not, you create an empty object on the fly. This way, the next level key will always be accessed from an object that exists or an empty object, but never from undefined.
2. Access Nested Objects Using Array Reduce
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', 'addresses', 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.
edited Jul 9 at 4:01
answered Jul 7 at 8:32
Dinesh Pandiyan
2,327825
2,327825
This question is primarily about access properties that exist. There is already a question about what you are referring to (and already including most of your solutions): Access Javascript nested objects safely or Accessing nested JavaScript objects with string key. But anyway: "Unfortunately, you cannot access nested arrays with this trick." Why not? Arrays are objects, so it should work just as well. Can you provide an example where it does not?
– Felix Kling
Jul 7 at 15:47
@FelixKling When we try to access arrays with Oliver Steele pattern, we won't be able to create array on 'n' length on the fly and access nth index without getting 'undefined' error. Ex.((user || {}).address || new Array(3))[1].name
– Dinesh Pandiyan
Jul 8 at 16:20
1
You are not applying your pattern consistently. Of course...[1].bar
would result in an error if the element1
didn't exist. But that's also the case for....foo.bar
iffoo
didn't exist. You have to "guard" accessing1
as well, just like you "guard" any other property access. An array is just an object. An "array element" is just a property. Correctly applied it would be(((user || {}).address || {})[1] || {}).name
.
– Felix Kling
Jul 9 at 3:49
This is great. It didn't strike me this way. Thank @FelixKling, I'll go update the blog posts.
– Dinesh Pandiyan
Jul 9 at 4:01
@DineshPandiyan you should disclose that you're the author of typy, I just came here after reading your blog post
– reggaeguitar
Sep 27 at 18:03
add a comment |
This question is primarily about access properties that exist. There is already a question about what you are referring to (and already including most of your solutions): Access Javascript nested objects safely or Accessing nested JavaScript objects with string key. But anyway: "Unfortunately, you cannot access nested arrays with this trick." Why not? Arrays are objects, so it should work just as well. Can you provide an example where it does not?
– Felix Kling
Jul 7 at 15:47
@FelixKling When we try to access arrays with Oliver Steele pattern, we won't be able to create array on 'n' length on the fly and access nth index without getting 'undefined' error. Ex.((user || {}).address || new Array(3))[1].name
– Dinesh Pandiyan
Jul 8 at 16:20
1
You are not applying your pattern consistently. Of course...[1].bar
would result in an error if the element1
didn't exist. But that's also the case for....foo.bar
iffoo
didn't exist. You have to "guard" accessing1
as well, just like you "guard" any other property access. An array is just an object. An "array element" is just a property. Correctly applied it would be(((user || {}).address || {})[1] || {}).name
.
– Felix Kling
Jul 9 at 3:49
This is great. It didn't strike me this way. Thank @FelixKling, I'll go update the blog posts.
– Dinesh Pandiyan
Jul 9 at 4:01
@DineshPandiyan you should disclose that you're the author of typy, I just came here after reading your blog post
– reggaeguitar
Sep 27 at 18:03
This question is primarily about access properties that exist. There is already a question about what you are referring to (and already including most of your solutions): Access Javascript nested objects safely or Accessing nested JavaScript objects with string key. But anyway: "Unfortunately, you cannot access nested arrays with this trick." Why not? Arrays are objects, so it should work just as well. Can you provide an example where it does not?
– Felix Kling
Jul 7 at 15:47
This question is primarily about access properties that exist. There is already a question about what you are referring to (and already including most of your solutions): Access Javascript nested objects safely or Accessing nested JavaScript objects with string key. But anyway: "Unfortunately, you cannot access nested arrays with this trick." Why not? Arrays are objects, so it should work just as well. Can you provide an example where it does not?
– Felix Kling
Jul 7 at 15:47
@FelixKling When we try to access arrays with Oliver Steele pattern, we won't be able to create array on 'n' length on the fly and access nth index without getting 'undefined' error. Ex.
((user || {}).address || new Array(3))[1].name
– Dinesh Pandiyan
Jul 8 at 16:20
@FelixKling When we try to access arrays with Oliver Steele pattern, we won't be able to create array on 'n' length on the fly and access nth index without getting 'undefined' error. Ex.
((user || {}).address || new Array(3))[1].name
– Dinesh Pandiyan
Jul 8 at 16:20
1
1
You are not applying your pattern consistently. Of course
...[1].bar
would result in an error if the element 1
didn't exist. But that's also the case for ....foo.bar
if foo
didn't exist. You have to "guard" accessing 1
as well, just like you "guard" any other property access. An array is just an object. An "array element" is just a property. Correctly applied it would be (((user || {}).address || {})[1] || {}).name
.– Felix Kling
Jul 9 at 3:49
You are not applying your pattern consistently. Of course
...[1].bar
would result in an error if the element 1
didn't exist. But that's also the case for ....foo.bar
if foo
didn't exist. You have to "guard" accessing 1
as well, just like you "guard" any other property access. An array is just an object. An "array element" is just a property. Correctly applied it would be (((user || {}).address || {})[1] || {}).name
.– Felix Kling
Jul 9 at 3:49
This is great. It didn't strike me this way. Thank @FelixKling, I'll go update the blog posts.
– Dinesh Pandiyan
Jul 9 at 4:01
This is great. It didn't strike me this way. Thank @FelixKling, I'll go update the blog posts.
– Dinesh Pandiyan
Jul 9 at 4:01
@DineshPandiyan you should disclose that you're the author of typy, I just came here after reading your blog post
– reggaeguitar
Sep 27 at 18:03
@DineshPandiyan you should disclose that you're the author of typy, I just came here after reading your blog post
– reggaeguitar
Sep 27 at 18:03
add a comment |
Using lodash would be good solution
Ex:
var object = { 'a': { 'b': { 'c': 3 } } };
_.get(object, 'a.b.c');
// => 3
How is this different from Access / process (nested) objects, arrays or JSON?
– Heretic Monkey
Feb 17 at 23:52
add a comment |
Using lodash would be good solution
Ex:
var object = { 'a': { 'b': { 'c': 3 } } };
_.get(object, 'a.b.c');
// => 3
How is this different from Access / process (nested) objects, arrays or JSON?
– Heretic Monkey
Feb 17 at 23:52
add a comment |
Using lodash would be good solution
Ex:
var object = { 'a': { 'b': { 'c': 3 } } };
_.get(object, 'a.b.c');
// => 3
Using lodash would be good solution
Ex:
var object = { 'a': { 'b': { 'c': 3 } } };
_.get(object, 'a.b.c');
// => 3
edited Sep 27 '17 at 12:34
Machavity
24.2k135479
24.2k135479
answered Sep 27 '17 at 12:31
pradeep gowda
42157
42157
How is this different from Access / process (nested) objects, arrays or JSON?
– Heretic Monkey
Feb 17 at 23:52
add a comment |
How is this different from Access / process (nested) objects, arrays or JSON?
– Heretic Monkey
Feb 17 at 23:52
How is this different from Access / process (nested) objects, arrays or JSON?
– Heretic Monkey
Feb 17 at 23:52
How is this different from Access / process (nested) objects, arrays or JSON?
– Heretic Monkey
Feb 17 at 23:52
add a comment |
protected by Samuel Liew♦ Oct 5 '15 at 8:58
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?
2
At least you shouldn't talk about "a JSON" if you're not talking about the JSON interchange format. This is just an object in literal notation.
– Marcel Korpel
Mar 1 '13 at 13:09
17
@Marcel: It has to be read as "I have a data nested data structure or JSON, how can I access a specific value?". I know the difference, but many people don't and might be searching for "JSON" rather than "object". Many questions actually are of the form "how can I access X in this JSON". The only place where I mention JSON in my answer is where I explain what it is. If you have a suggestion how to communicate this in a better way, I'm all ears.
– Felix Kling
Mar 2 '13 at 0:46
possible duplicate of JSON find in JavaScript
– Travis J
Jun 12 '13 at 22:14