I have an array of JavaScript objects:
var objs = [
{ first_nom: 'Lazslo', last_nom: 'Jamf' },
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
];
How can I sort them by the value of last_nom in JavaScript?
I know about sort(a,b), but that only seems to work on strings and numbers. Do I need to add a toString() method to my objects?
It's easy enough to write your own comparison function:
function compare( a, b ) {
if ( a.last_nom < b.last_nom ){
return -1;
}
if ( a.last_nom > b.last_nom ){
return 1;
}
return 0;
}
objs.sort( compare );
Or inline (c/o Marco Demaio):
objs.sort((a,b) => (a.last_nom > b.last_nom) ? 1 : ((b.last_nom > a.last_nom) ? -1 : 0))
Or simplified for numeric (c/o Andre Figueiredo):
objs.sort((a,b) => a.last_nom - b.last_nom); // b - a for reverse sort
You can also create a dynamic sort function that sorts objects by their value that you pass:
function dynamicSort(property) {
var sortOrder = 1;
if(property[0] === "-") {
sortOrder = -1;
property = property.substr(1);
}
return function (a,b) {
/* next line works with strings and numbers,
* and you may want to customize it to your needs
*/
var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
return result * sortOrder;
}
}
So you can have an array of objects like this:
var People = [
{Name: "Name", Surname: "Surname"},
{Name:"AAA", Surname:"ZZZ"},
{Name: "Name", Surname: "AAA"}
];
...and it will work when you do:
People.sort(dynamicSort("Name"));
People.sort(dynamicSort("Surname"));
People.sort(dynamicSort("-Surname"));
Actually this already answers the question. Below part is written because many people contacted me, complaining that it doesn't work with multiple parameters.
Multiple Parameters
You can use the function below to generate sort functions with multiple sort parameters.
function dynamicSortMultiple() {
/*
* save the arguments object as it will be overwritten
* note that arguments object is an array-like object
* consisting of the names of the properties to sort by
*/
var props = arguments;
return function (obj1, obj2) {
var i = 0, result = 0, numberOfProperties = props.length;
/* try getting a different result from 0 (equal)
* as long as we have extra properties to compare
*/
while(result === 0 && i < numberOfProperties) {
result = dynamicSort(props[i])(obj1, obj2);
i++;
}
return result;
}
}
Which would enable you to do something like this:
People.sort(dynamicSortMultiple("Name", "-Surname"));
Subclassing Array
For the lucky among us who can use ES6, which allows extending the native objects:
class MyArray extends Array {
sortBy(...args) {
return this.sort(dynamicSortMultiple(...args));
}
}
That would enable this:
MyArray.from(People).sortBy("Name", "-Surname");
In ES6/ES2015 or later you can do it this way:
objs.sort((a, b) => a.last_nom.localeCompare(b.last_nom));
Prior to ES6/ES2015
objs.sort(function(a, b) {
return a.last_nom.localeCompare(b.last_nom)
});
Underscore.js
Use Underscore.js]. It’s small and awesome...
sortBy_.sortBy(list, iterator, [context]) Returns a sorted copy of
list, ranked in ascending order by the results of running each value
through iterator. Iterator may also be the string name of the property
to sort by (eg. length).
var objs = [
{ first_nom: 'Lazslo',last_nom: 'Jamf' },
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
];
var sortedObjs = _.sortBy(objs, 'first_nom');
Case sensitive
arr.sort((a, b) => a.name > b.name ? 1 : -1);
Case Insensitive
arr.sort((a, b) => a.name.toLowerCase() > b.name.toLowerCase() ? 1 : -1);
Useful Note
If no change in order (in case of the same strings) then the condition > will fail and -1 will be returned. But if strings are same then returning 1 or -1 will result in correct output
The other option could be to use >= operator instead of >
var objs = [
{ first_nom: 'Lazslo', last_nom: 'Jamf' },
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
];
// Define a couple of sorting callback functions, one with hardcoded sort key and the other with an argument sort key
const sorter1 = (a, b) => a.last_nom.toLowerCase() > b.last_nom.toLowerCase() ? 1 : -1;
const sorter2 = (sortBy) => (a, b) => a[sortBy].toLowerCase() > b[sortBy].toLowerCase() ? 1 : -1;
objs.sort(sorter1);
console.log("Using sorter1 - Hardcoded sort property last_name", objs);
objs.sort(sorter2('first_nom'));
console.log("Using sorter2 - passed param sortBy='first_nom'", objs);
objs.sort(sorter2('last_nom'));
console.log("Using sorter2 - passed param sortBy='last_nom'", objs);
If you have duplicate last names you might sort those by first name-
obj.sort(function(a,b){
if(a.last_nom< b.last_nom) return -1;
if(a.last_nom >b.last_nom) return 1;
if(a.first_nom< b.first_nom) return -1;
if(a.first_nom >b.first_nom) return 1;
return 0;
});
As of 2018 there is a much shorter and elegant solution. Just use. Array.prototype.sort().
Example:
var items = [
{ name: 'Edward', value: 21 },
{ name: 'Sharpe', value: 37 },
{ name: 'And', value: 45 },
{ name: 'The', value: -12 },
{ name: 'Magnetic', value: 13 },
{ name: 'Zeros', value: 37 }
];
// sort by value
items.sort(function (a, b) {
return a.value - b.value;
});
Simple and quick solution to this problem using prototype inheritance:
Array.prototype.sortBy = function(p) {
return this.slice(0).sort(function(a,b) {
return (a[p] > b[p]) ? 1 : (a[p] < b[p]) ? -1 : 0;
});
}
Example / Usage
objs = [{age:44,name:'vinay'},{age:24,name:'deepak'},{age:74,name:'suresh'}];
objs.sortBy('age');
// Returns
// [{"age":24,"name":"deepak"},{"age":44,"name":"vinay"},{"age":74,"name":"suresh"}]
objs.sortBy('name');
// Returns
// [{"age":24,"name":"deepak"},{"age":74,"name":"suresh"},{"age":44,"name":"vinay"}]
Update: No longer modifies original array.
Old answer that is not correct:
arr.sort((a, b) => a.name > b.name)
UPDATE
From Beauchamp's comment:
arr.sort((a, b) => a.name < b.name ? -1 : (a.name > b.name ? 1 : 0))
More readable format:
arr.sort((a, b) => {
if (a.name < b.name) return -1
return a.name > b.name ? 1 : 0
})
Without nested ternaries:
arr.sort((a, b) => a.name < b.name ? - 1 : Number(a.name > b.name))
Explanation: Number() will cast true to 1 and false to 0.
Lodash (a superset of Underscore.js).
It's good not to add a framework for every simple piece of logic, but relying on well tested utility frameworks can speed up development and reduce the amount of bugs.
Lodash produces very clean code and promotes a more functional programming style. In one glimpse, it becomes clear what the intent of the code is.
The OP's issue can simply be solved as:
const sortedObjs = _.sortBy(objs, 'last_nom');
More information? For example, we have the following nested object:
const users = [
{ 'user': {'name':'fred', 'age': 48}},
{ 'user': {'name':'barney', 'age': 36 }},
{ 'user': {'name':'wilma'}},
{ 'user': {'name':'betty', 'age': 32}}
];
We now can use the _.property shorthand user.age to specify the path to the property that should be matched. We will sort the user objects by the nested age property. Yes, it allows for nested property matching!
const sortedObjs = _.sortBy(users, ['user.age']);
Want it reversed? No problem. Use _.reverse.
const sortedObjs = _.reverse(_.sortBy(users, ['user.age']));
Want to combine both using chain?
const { chain } = require('lodash');
const sortedObjs = chain(users).sortBy('user.age').reverse().value();
Or when do you prefer flow over chain?
const { flow, reverse, sortBy } = require('lodash/fp');
const sortedObjs = flow([sortBy('user.age'), reverse])(users);
You can use
Easiest Way: Lodash
(https://lodash.com/docs/4.17.10#orderBy)
This method is like _.sortBy except that it allows specifying the sort orders of the iteratees to sort by. If orders is unspecified, all values are sorted in ascending order. Otherwise, specify an order of "desc" for descending or "asc" for ascending sort order of corresponding values.
Arguments
collection (Array|Object): The collection to iterate over.
[iteratees=[_.identity]] (Array[]|Function[]|Object[]|string[]): The iteratees to sort by.
[orders] (string[]): The sort orders of iteratees.
Returns
(Array): Returns the new sorted array.
var _ = require('lodash');
var homes = [
{"h_id":"3",
"city":"Dallas",
"state":"TX",
"zip":"75201",
"price":"162500"},
{"h_id":"4",
"city":"Bevery Hills",
"state":"CA",
"zip":"90210",
"price":"319250"},
{"h_id":"6",
"city":"Dallas",
"state":"TX",
"zip":"75000",
"price":"556699"},
{"h_id":"5",
"city":"New York",
"state":"NY",
"zip":"00010",
"price":"962500"}
];
_.orderBy(homes, ['city', 'state', 'zip'], ['asc', 'desc', 'asc']);
I haven't seen this particular approach suggested, so here's a terse comparison method I like to use that works for both string and number types:
const objs = [
{ first_nom: 'Lazslo', last_nom: 'Jamf' },
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
];
const sortBy = fn => {
const cmp = (a, b) => -(a < b) || +(a > b);
return (a, b) => cmp(fn(a), fn(b));
};
const getLastName = o => o.last_nom;
const sortByLastName = sortBy(getLastName);
objs.sort(sortByLastName);
console.log(objs.map(getLastName));
Explanation of sortBy()
sortBy() accepts a fn that selects a value from an object to use in comparison, and returns a function that can be passed to Array.prototype.sort(). In this example, we're comparing o.last_nom. Whenever we receive two objects such as
a = { first_nom: 'Lazslo', last_nom: 'Jamf' }
b = { first_nom: 'Pig', last_nom: 'Bodine' }
we compare them with (a, b) => cmp(fn(a), fn(b)). Given that
fn = o => o.last_nom
we can expand the comparison function to (a, b) => cmp(a.last_nom, b.last_nom). Because of the way logical OR (||) works in JavaScript, cmp(a.last_nom, b.last_nom) is equivalent to
if (a.last_nom < b.last_nom) return -1;
if (a.last_nom > b.last_nom) return 1;
return 0;
Incidentally, this is called the three-way comparison "spaceship" (<=>) operator in other languages.
Finally, here's the ES5-compatible syntax without using arrow functions:
var objs = [
{ first_nom: 'Lazslo', last_nom: 'Jamf' },
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
];
function sortBy(fn) {
function cmp(a, b) { return -(a < b) || +(a > b); }
return function (a, b) { return cmp(fn(a), fn(b)); };
}
function getLastName(o) { return o.last_nom; }
var sortByLastName = sortBy(getLastName);
objs.sort(sortByLastName);
console.log(objs.map(getLastName));
Instead of using a custom comparison function, you could also create an object type with custom toString() method (which is invoked by the default comparison function):
function Person(firstName, lastName) {
this.firtName = firstName;
this.lastName = lastName;
}
Person.prototype.toString = function() {
return this.lastName + ', ' + this.firstName;
}
var persons = [ new Person('Lazslo', 'Jamf'), ...]
persons.sort();
There are many good answers here, but I would like to point out that they can be extended very simply to achieve a lot more complex sorting. The only thing you have to do is to use the OR operator to chain comparison functions like this:
objs.sort((a,b)=> fn1(a,b) || fn2(a,b) || fn3(a,b) )
Where fn1, fn2, ... are the sort functions which return [-1,0,1]. This results in "sorting by fn1" and "sorting by fn2" which is pretty much equal to ORDER BY in SQL.
This solution is based on the behaviour of || operator which evaluates to the first evaluated expression which can be converted to true.
The simplest form has only one inlined function like this:
// ORDER BY last_nom
objs.sort((a,b)=> a.last_nom.localeCompare(b.last_nom) )
Having two steps with last_nom,first_nom sort order would look like this:
// ORDER_BY last_nom, first_nom
objs.sort((a,b)=> a.last_nom.localeCompare(b.last_nom) ||
a.first_nom.localeCompare(b.first_nom) )
A generic comparison function could be something like this:
// ORDER BY <n>
let cmp = (a,b,n)=>a[n].localeCompare(b[n])
This function could be extended to support numeric fields, case-sensitivity, arbitrary data types, etc.
You can use them by chaining them by sort priority:
// ORDER_BY last_nom, first_nom
objs.sort((a,b)=> cmp(a,b, "last_nom") || cmp(a,b, "first_nom") )
// ORDER_BY last_nom, first_nom DESC
objs.sort((a,b)=> cmp(a,b, "last_nom") || -cmp(a,b, "first_nom") )
// ORDER_BY last_nom DESC, first_nom DESC
objs.sort((a,b)=> -cmp(a,b, "last_nom") || -cmp(a,b, "first_nom") )
The point here is that pure JavaScript with functional approach can take you a long way without external libraries or complex code. It is also very effective, since no string parsing have to be done.
Try this:
Up to ES5
// Ascending sort
items.sort(function (a, b) {
return a.value - b.value;
});
// Descending sort
items.sort(function (a, b) {
return b.value - a.value;
});
In ES6 and above
// Ascending sort
items.sort((a, b) => a.value - b.value);
// Descending sort
items.sort((a, b) => b.value - a.value);
Use JavaScript sort method
The sort method can be modified to sort anything like an array of numbers, strings and even objects using a compare function.
A compare function is passed as an optional argument to the sort method.
This compare function accepts 2 arguments generally called a and b. Based on these 2 arguments you can modify the sort method to work as you want.
If the compare function returns less than 0, then the sort() method sorts a at a lower index than b. Simply a will come before b.
If the compare function returns equal to 0, then the sort() method leaves the element positions as they are.
If the compare function returns greater than 0, then the sort() method sorts a at greater index than b. Simply a will come after b.
Use the above concept to apply on your object where a will be your object property.
var objs = [
{ first_nom: 'Lazslo', last_nom: 'Jamf' },
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
];
function compare(a, b) {
if (a.last_nom > b.last_nom) return 1;
if (a.last_nom < b.last_nom) return -1;
return 0;
}
objs.sort(compare);
console.log(objs)
// for better look use console.table(objs)
Example Usage:
objs.sort(sortBy('last_nom'));
Script:
/**
* #description
* Returns a function which will sort an
* array of objects by the given key.
*
* #param {String} key
* #param {Boolean} reverse
* #return {Function}
*/
const sortBy = (key, reverse) => {
// Move smaller items towards the front
// or back of the array depending on if
// we want to sort the array in reverse
// order or not.
const moveSmaller = reverse ? 1 : -1;
// Move larger items towards the front
// or back of the array depending on if
// we want to sort the array in reverse
// order or not.
const moveLarger = reverse ? -1 : 1;
/**
* #param {*} a
* #param {*} b
* #return {Number}
*/
return (a, b) => {
if (a[key] < b[key]) {
return moveSmaller;
}
if (a[key] > b[key]) {
return moveLarger;
}
return 0;
};
};
Write short code:
objs.sort((a, b) => a.last_nom > b.last_nom ? 1 : -1)
I didn't see any implementation similar to mine. This version is based on the Schwartzian transform idiom.
function sortByAttribute(array, ...attrs) {
// Generate an array of predicate-objects containing
// property getter, and descending indicator
let predicates = attrs.map(pred => {
let descending = pred.charAt(0) === '-' ? -1 : 1;
pred = pred.replace(/^-/, '');
return {
getter: o => o[pred],
descend: descending
};
});
// Schwartzian transform idiom implementation. AKA "decorate-sort-undecorate"
return array.map(item => {
return {
src: item,
compareValues: predicates.map(predicate => predicate.getter(item))
};
})
.sort((o1, o2) => {
let i = -1, result = 0;
while (++i < predicates.length) {
if (o1.compareValues[i] < o2.compareValues[i])
result = -1;
if (o1.compareValues[i] > o2.compareValues[i])
result = 1;
if (result *= predicates[i].descend)
break;
}
return result;
})
.map(item => item.src);
}
Here's an example how to use it:
let games = [
{ name: 'Mashraki', rating: 4.21 },
{ name: 'Hill Climb Racing', rating: 3.88 },
{ name: 'Angry Birds Space', rating: 3.88 },
{ name: 'Badland', rating: 4.33 }
];
// Sort by one attribute
console.log(sortByAttribute(games, 'name'));
// Sort by mupltiple attributes
console.log(sortByAttribute(games, '-rating', 'name'));
Sorting (more) Complex Arrays of Objects
Since you probably encounter more complex data structures like this array, I would expand the solution.
TL;DR
Are more pluggable version based on #ege-Özcan's very lovely answer.
Problem
I encountered the below and couldn't change it. I also did not want to flatten the object temporarily. Nor did I want to use underscore / lodash, mainly for performance reasons and the fun to implement it myself.
var People = [
{Name: {name: "Name", surname: "Surname"}, Middlename: "JJ"},
{Name: {name: "AAA", surname: "ZZZ"}, Middlename:"Abrams"},
{Name: {name: "Name", surname: "AAA"}, Middlename: "Wars"}
];
Goal
The goal is to sort it primarily by People.Name.name and secondarily by People.Name.surname
Obstacles
Now, in the base solution uses bracket notation to compute the properties to sort for dynamically. Here, though, we would have to construct the bracket notation dynamically also, since you would expect some like People['Name.name'] would work - which doesn't.
Simply doing People['Name']['name'], on the other hand, is static and only allows you to go down the n-th level.
Solution
The main addition here will be to walk down the object tree and determine the value of the last leaf, you have to specify, as well as any intermediary leaf.
var People = [
{Name: {name: "Name", surname: "Surname"}, Middlename: "JJ"},
{Name: {name: "AAA", surname: "ZZZ"}, Middlename:"Abrams"},
{Name: {name: "Name", surname: "AAA"}, Middlename: "Wars"}
];
People.sort(dynamicMultiSort(['Name','name'], ['Name', '-surname']));
// Results in...
// [ { Name: { name: 'AAA', surname: 'ZZZ' }, Middlename: 'Abrams' },
// { Name: { name: 'Name', surname: 'Surname' }, Middlename: 'JJ' },
// { Name: { name: 'Name', surname: 'AAA' }, Middlename: 'Wars' } ]
// same logic as above, but strong deviation for dynamic properties
function dynamicSort(properties) {
var sortOrder = 1;
// determine sort order by checking sign of last element of array
if(properties[properties.length - 1][0] === "-") {
sortOrder = -1;
// Chop off sign
properties[properties.length - 1] = properties[properties.length - 1].substr(1);
}
return function (a,b) {
propertyOfA = recurseObjProp(a, properties)
propertyOfB = recurseObjProp(b, properties)
var result = (propertyOfA < propertyOfB) ? -1 : (propertyOfA > propertyOfB) ? 1 : 0;
return result * sortOrder;
};
}
/**
* Takes an object and recurses down the tree to a target leaf and returns it value
* #param {Object} root - Object to be traversed.
* #param {Array} leafs - Array of downwards traversal. To access the value: {parent:{ child: 'value'}} -> ['parent','child']
* #param {Number} index - Must not be set, since it is implicit.
* #return {String|Number} The property, which is to be compared by sort.
*/
function recurseObjProp(root, leafs, index) {
index ? index : index = 0
var upper = root
// walk down one level
lower = upper[leafs[index]]
// Check if last leaf has been hit by having gone one step too far.
// If so, return result from last step.
if (!lower) {
return upper
}
// Else: recurse!
index++
// HINT: Bug was here, for not explicitly returning function
// https://stackoverflow.com/a/17528613/3580261
return recurseObjProp(lower, leafs, index)
}
/**
* Multi-sort your array by a set of properties
* #param {...Array} Arrays to access values in the form of: {parent:{ child: 'value'}} -> ['parent','child']
* #return {Number} Number - number for sort algorithm
*/
function dynamicMultiSort() {
var args = Array.prototype.slice.call(arguments); // slight deviation to base
return function (a, b) {
var i = 0, result = 0, numberOfProperties = args.length;
// REVIEW: slightly verbose; maybe no way around because of `.sort`-'s nature
// Consider: `.forEach()`
while(result === 0 && i < numberOfProperties) {
result = dynamicSort(args[i])(a, b);
i++;
}
return result;
}
}
Example
Working example on JSBin
Combining Ege's dynamic solution with Vinay's idea, you get a nice robust solution:
Array.prototype.sortBy = function() {
function _sortByAttr(attr) {
var sortOrder = 1;
if (attr[0] == "-") {
sortOrder = -1;
attr = attr.substr(1);
}
return function(a, b) {
var result = (a[attr] < b[attr]) ? -1 : (a[attr] > b[attr]) ? 1 : 0;
return result * sortOrder;
}
}
function _getSortFunc() {
if (arguments.length == 0) {
throw "Zero length arguments not allowed for Array.sortBy()";
}
var args = arguments;
return function(a, b) {
for (var result = 0, i = 0; result == 0 && i < args.length; i++) {
result = _sortByAttr(args[i])(a, b);
}
return result;
}
}
return this.sort(_getSortFunc.apply(null, arguments));
}
Usage:
// Utility for printing objects
Array.prototype.print = function(title) {
console.log("************************************************************************");
console.log("**** " + title);
console.log("************************************************************************");
for (var i = 0; i < this.length; i++) {
console.log("Name: " + this[i].FirstName, this[i].LastName, "Age: " + this[i].Age);
}
}
// Setup sample data
var arrObj = [{
FirstName: "Zach",
LastName: "Emergency",
Age: 35
},
{
FirstName: "Nancy",
LastName: "Nurse",
Age: 27
},
{
FirstName: "Ethel",
LastName: "Emergency",
Age: 42
},
{
FirstName: "Nina",
LastName: "Nurse",
Age: 48
},
{
FirstName: "Anthony",
LastName: "Emergency",
Age: 44
},
{
FirstName: "Nina",
LastName: "Nurse",
Age: 32
},
{
FirstName: "Ed",
LastName: "Emergency",
Age: 28
},
{
FirstName: "Peter",
LastName: "Physician",
Age: 58
},
{
FirstName: "Al",
LastName: "Emergency",
Age: 51
},
{
FirstName: "Ruth",
LastName: "Registration",
Age: 62
},
{
FirstName: "Ed",
LastName: "Emergency",
Age: 38
},
{
FirstName: "Tammy",
LastName: "Triage",
Age: 29
},
{
FirstName: "Alan",
LastName: "Emergency",
Age: 60
},
{
FirstName: "Nina",
LastName: "Nurse",
Age: 54
}
];
//Unit Tests
arrObj.sortBy("LastName").print("LastName Ascending");
arrObj.sortBy("-LastName").print("LastName Descending");
arrObj.sortBy("LastName", "FirstName", "-Age").print("LastName Ascending, FirstName Ascending, Age Descending");
arrObj.sortBy("-FirstName", "Age").print("FirstName Descending, Age Ascending");
arrObj.sortBy("-Age").print("Age Descending");
One more option:
var someArray = [...];
function generateSortFn(prop, reverse) {
return function (a, b) {
if (a[prop] < b[prop]) return reverse ? 1 : -1;
if (a[prop] > b[prop]) return reverse ? -1 : 1;
return 0;
};
}
someArray.sort(generateSortFn('name', true));
It sorts ascending by default.
A simple way:
objs.sort(function(a,b) {
return b.last_nom.toLowerCase() < a.last_nom.toLowerCase();
});
See that '.toLowerCase()' is necessary to prevent erros
in comparing strings.
Warning!
Using this solution is not recommended as it does not result in a sorted array. It is being left here for future reference, because the idea is not rare.
objs.sort(function(a,b){return b.last_nom>a.last_nom})
This is my take on this:
The order parameter is optional and defaults to "ASC" for ascending order.
It works on accented characters and it's case insensitive.
Note: It sorts and returns the original array.
function sanitizeToSort(str) {
return str
.normalize('NFD') // Remove accented and diacritics
.replace(/[\u0300-\u036f]/g, '') // Remove accented and diacritics
.toLowerCase() // Sort will be case insensitive
;
}
function sortByProperty(arr, property, order="ASC") {
arr.forEach((item) => item.tempProp = sanitizeToSort(item[property]));
arr.sort((a, b) => order === "ASC" ?
a.tempProp > b.tempProp ? 1 : a.tempProp < b.tempProp ? -1 : 0
: a.tempProp > b.tempProp ? -1 : a.tempProp < b.tempProp ? 1 : 0
);
arr.forEach((item) => delete item.tempProp);
return arr;
}
Snippet
function sanitizeToSort(str) {
return str
.normalize('NFD') // Remove accented characters
.replace(/[\u0300-\u036f]/g, '') // Remove diacritics
.toLowerCase()
;
}
function sortByProperty(arr, property, order="ASC") {
arr.forEach((item) => item.tempProp = sanitizeToSort(item[property]));
arr.sort((a, b) => order === "ASC" ?
a.tempProp > b.tempProp ? 1 : a.tempProp < b.tempProp ? -1 : 0
: a.tempProp > b.tempProp ? -1 : a.tempProp < b.tempProp ? 1 : 0
);
arr.forEach((item) => delete item.tempProp);
return arr;
}
const rockStars = [
{ name: "Axl",
lastname: "Rose" },
{ name: "Elthon",
lastname: "John" },
{ name: "Paul",
lastname: "McCartney" },
{ name: "Lou",
lastname: "Reed" },
{ name: "freddie", // Works on lower/upper case
lastname: "mercury" },
{ name: "Ámy", // Works on accented characters too
lastname: "winehouse"}
];
sortByProperty(rockStars, "name");
console.log("Ordered by name A-Z:");
rockStars.forEach((item) => console.log(item.name + " " + item.lastname));
sortByProperty(rockStars, "lastname", "DESC");
console.log("\nOrdered by lastname Z-A:");
rockStars.forEach((item) => console.log(item.lastname + ", " + item.name));
A simple function that sorts an array of object by a property:
function sortArray(array, property, direction) {
direction = direction || 1;
array.sort(function compare(a, b) {
let comparison = 0;
if (a[property] > b[property]) {
comparison = 1 * direction;
} else if (a[property] < b[property]) {
comparison = -1 * direction;
}
return comparison;
});
return array; // Chainable
}
Usage:
var objs = [
{ first_nom: 'Lazslo', last_nom: 'Jamf' },
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
];
sortArray(objs, "last_nom"); // Asc
sortArray(objs, "last_nom", -1); // Desc
Given the original example:
var objs = [
{ first_nom: 'Lazslo', last_nom: 'Jamf' },
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
];
Sort by multiple fields:
objs.sort(function(left, right) {
var last_nom_order = left.last_nom.localeCompare(right.last_nom);
var first_nom_order = left.first_nom.localeCompare(right.first_nom);
return last_nom_order || first_nom_order;
});
Notes
a.localeCompare(b) is universally supported and returns -1,0,1 if a<b,a==b,a>b respectively.
|| in the last line gives last_nom priority over first_nom.
Subtraction works on numeric fields: var age_order = left.age - right.age;
Negate to reverse order, return -last_nom_order || -first_nom_order || -age_order;
Additional desc parameters for Ege Özcan's code:
function dynamicSort(property, desc) {
if (desc) {
return function (a, b) {
return (a[property] > b[property]) ? -1 : (a[property] < b[property]) ? 1 : 0;
}
}
return function (a, b) {
return (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
}
}
Using Ramda,
npm install ramda
import R from 'ramda'
var objs = [
{ first_nom: 'Lazslo', last_nom: 'Jamf' },
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
];
var ascendingSortedObjs = R.sortBy(R.prop('last_nom'), objs)
var descendingSortedObjs = R.reverse(ascendingSortedObjs)
function compare(propName) {
return function(a,b) {
if (a[propName] < b[propName])
return -1;
if (a[propName] > b[propName])
return 1;
return 0;
};
}
objs.sort(compare("last_nom"));
Related
I have a JSON file and I am trying to calculate the JSON file key based on the value and reformating it. My JSON file looks like below:
data=[
{
pet:'Cat',
fruit:'Apple',
fish:'Hilsha'
},
{
pet:'Dog',
fish:'Carp'
},
{
pet:'Cat',
fruit:'Orange',
fish:'Lobster'
}
];
I do like to calculate and formate it like below:
data=[
{
label:'Pet',
total:3,
list:[
{
name:'Cat',
value: 2,
},
{
name:'Dog',
value: 1,
}
]
},
{
label:'Fruit',
total:2,
list:[
{
name:'Apple',
value: 1,
},
{
name:'Orange',
value: 1,
}
]
},
{
label:'Fish',
total:3,
list:[
{
name:'Hilsha',
value: 1,
},
{
name:'Carp',
value: 1,
},
{
name:'Lobster',
value: 1,
}
]
},
];
If anybody can help me, it will be very help for me and will save a day.
I have fixed this task myself. If I have any wrong, you can put your comment fill-free :)
``
ngOnInit(): void {
this.dataService.$data.subscribe(data => {
// Create new object and calculation according to category
let petObj: any = {}
let fruitObj: any = {}
let fishObj: any = {}
data.forEach((el: any) => {
if (el.pet != undefined) {
petObj[el.pet] = (petObj[el.pet] || 0) + 1;
}
if (el.fruit != undefined) {
fruitObj[el.fruit] = (fruitObj[el.fruit] || 0) + 1;
}
if (el.fish != undefined) {
fishObj[el.fish] = (fishObj[el.fish] || 0) + 1;
}
});
// Create list according to category
let pet_list: any = [];
let fruit_list: any = [];
let fish_list: any = [];
for (var key in petObj) {
let pet = {
label: key,
value: petObj[key]
}
pet_list.push(pet)
}
for (var key in fruitObj) {
let fruit = {
label: key,
value: fruitObj[key]
}
fruit_list.push(fruit)
}
for (var key in fishObj) {
let fish = {
label: key,
value: fishObj[key]
}
fish_list.push(fish)
}
// Calculate total sum according to category
var totalPet = pet_list.map((res: any) => res.value).reduce((a: any, b: any) => a + b);
var totalFruit = fruit_list.map((res: any) => res.value).reduce((a: any, b: any) => a + b);
var totalFish = fish_list.map((res: any) => res.value).reduce((a: any, b: any) => a + b);
// Rearrange the JSON
this.rearrangeData = [
{
label: 'Pet',
total: totalPet,
list: pet_list
},
{
label: 'Fruit',
total: totalFruit,
list: fruit_list
},
{
label: 'Fish',
total: totalFish,
list: fish_list
}
]
console.log(this.rearrangeData)
// End rearrange the JSON
});
}
``
You can simplify your function. Take a look this one
group(oldData) {
const data = []; //declare an empty array
oldData.forEach((x) => {
//x will be {pet: 'Cat',fruit: 'Apple',fish: 'Hilsha'},
// {pet: 'Dog',fish: 'Carp'}
// ...
Object.keys(x).forEach((key) => {
//key will be 'pet','fruit',...
const item = data.find((d) => d.label == key); //search in the "data array"
if (item) { //if find it
item.total++; //add 1 to the property total of the element find it
// and search in the item.list the 'Cat'
const list = item.list.find((l) => l.name == x[key]);
//if find it add 1 to the property value of the list
if (list)
list.value++;
else
//if not, add to the list
//an object with property "name" and "value" equal 1
item.list.push({ name: x[key], value: 1 });
} else
//if the element is not in the "array data"
//add an object with properties label, total and list
//see that list is an array with an unique element
data.push({
label: key,
total: 1,
list: [{ name: x[key], value: 1 }],
});
});
});
return data;
}
You can use like
this.dataService.$data.subscribe(data => {
this.rearrangeData=this.group(data)
}
NOTE: this function the labels are 'pet','fruit' and 'fish' not 'Pet', 'Fruit' and 'Fish'
Did you try reading the text leading up to this exercise? That'd be my first approach. After that, I'd use reduce. You can do pretty much anything with reduce.
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?
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.
You can access it this way
data.items[1].name
or
data["items"][1]["name"]
Both ways are equal.
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
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.
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.
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.
It's simple explanation:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
/*
1. `data` is object contain `items` object*/
console.log(data);
/*
2. `items` object contain array of two objects as elements*/
console.log(data.items);
/*
3. you need 2nd element of array - the `1` from `[0, 1]`*/
console.log(data.items[1]);
/*
4. and you need value of `name` property of 2nd object-element of array)*/
console.log(data.items[1].name);
Here are 4 different methods mentioned to get the javascript object property:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
// Method 1
let method1 = data.items[1].name;
console.log(method1);
// Method 2
let method2 = data.items[1]["name"];
console.log(method2);
// Method 3
let method3 = data["items"][1]["name"];
console.log(method3);
// Method 4 Destructuring
let { items: [, { name: second_name }] } = data;
console.log(second_name);
You could use lodash _get function:
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.get(object, 'a[0].b.c');
// => 3
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.
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/
Another more useful document depicting the situation above:
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Basics#Bracket_notation
Property access via dot walking: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#Dot_notation
Accessing dynamically multi levels object.
var obj = {
name: "john doe",
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/
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.
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");
I prefer JQuery. It's cleaner and easy to read.
$.each($.parseJSON(data), function (key, value) {
alert(value.<propertyname>);
});
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 firstand firstOrDefaultrespectively. 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
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);
}
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.
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>
In 2020, you can use #babel/plugin-proposal-optional-chaining it is very easy to access nested values in an object.
const obj = {
foo: {
bar: {
baz: class {
},
},
},
};
const baz = new obj?.foo?.bar?.baz(); // baz instance
const safe = new obj?.qux?.baz(); // undefined
const safe2 = new obj?.foo.bar.qux?.(); // undefined
https://babeljs.io/docs/en/babel-plugin-proposal-optional-chaining
https://github.com/tc39/proposal-optional-chaining
Dynamic approach
In below deep(data,key) function, you can use arbitrary key string - in your case items[1].name (you can use array notation [i] at any level) - if key is invalid then undefined is return.
let deep = (o,k) => k.split('.').reduce((a,c,i) => {
let m=c.match(/(.*?)\[(\d*)\]/);
if(m && a!=null && a[m[1]]!=null) return a[m[1]][+m[2]];
return a==null ? a: a[c];
},o);
// TEST
let key = 'items[1].name' // arbitrary deep-key
let data = {
code: 42,
items: [{ id: 11, name: 'foo'}, { id: 22, name: 'bar'},]
};
console.log( key,'=', deep(data,key) );
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>
You can use the syntax jsonObject.key to access the the value. And if you want access a value from an array, then you can use the syntax jsonObjectArray[index].key.
Here are the code examples to access various values to give you the idea.
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
// if you want 'bar'
console.log(data.items[1].name);
// if you want array of item names
console.log(data.items.map(x => x.name));
// get the id of the item where name = 'bar'
console.log(data.items.filter(x => (x.name == "bar") ? x.id : null)[0].id);
this is how i have done this.
let groups = [
{
id:1,
title:"Group 1",
members:[
{
id:1,
name:"Aftab",
battry:'10%'
},
{
id:2,
name:"Jamal",
},
{
id:3,
name:"Hamid",
},
{
id:4,
name:"Aqeel",
},
]
},
{
id:2,
title:"Group 2",
members:[
{
id:1,
name:"Aftab",
battry:'10%'
},
{
id:2,
name:"Jamal",
battry:'10%'
},
{
id:3,
name:"Hamid",
},
]
},
{
id:3,
title:"Group 3",
members:[
{
id:1,
name:"Aftab",
battry:'10%'
},
{
id:3,
name:"Hamid",
},
{
id:4,
name:"Aqeel",
},
]
}
]
groups.map((item) => {
// if(item.id == 2){
item.members.map((element) => {
if(element.id == 1){
element.battry="20%"
}
})
//}
})
groups.forEach((item) => {
item.members.forEach((item) => {
console.log(item)
})
})
If you're trying to find a path in a JSON string, you can dump your data into https://jsonpathfinder.com and click on the GUI elements. It'll generate the JS syntax for the path to the element.
Beyond that, for any arrays you might want to iterate, replace the relevant array offset indices like [0] with a loop.
Here's a simpler version of the tool you can run here, or at https://ggorlen.github.io/json-dive/. Click the node you want to copy the path to your clipboard.
/* code minified to make the tool easier to run without having to scroll */ let bracketsOnly=!1,lastHighlighted={style:{}};const keyToStr=t=>!bracketsOnly&&/^[a-zA-Z_$][a-zA-Z$_\d]*$/.test(t)?`.${toHTML(t)}`:`["${toHTML(t)}"]`,pathToData=t=>`data-path="data${t.join("")}"`,htmlSpecialChars={"&":"&","<":"<",">":">",'"':""","'":"'","\t":"\\t","\r":"\\r","\n":"\\n"," ":" "},toHTML=t=>(""+t).replace(/[&<>"'\t\r\n ]/g,t=>htmlSpecialChars[t]),makeArray=(t,e)=>`\n [<ul ${pathToData(e)}>\n ${t.map((t,a)=>{e.push(`[${a}]`);const n=`<li ${pathToData(e)}>\n ${pathify(t,e).trim()},\n </li>`;return e.pop(),n}).join("")}\n </ul>]\n`,makeObj=(t,e)=>`\n {<ul ${pathToData(e)}>\n ${Object.entries(t).map(([t,a])=>{e.push(keyToStr(t));const n=`<li ${pathToData(e)}>\n "${toHTML(t)}": ${pathify(a,e).trim()},\n </li>`;return e.pop(),n}).join("")}\n </ul>}\n`,pathify=(t,e=[])=>Array.isArray(t)?makeArray(t,e):"object"==typeof t&&t!=null?makeObj(t,e):toHTML("string"==typeof t?`"${t}"`:t),defaultJSON='{\n "corge": "test JSON... \\n asdf\\t asdf",\n "foo-bar": [\n {"id": 42},\n [42, {"foo": {"baz": {"ba r<>!\\t": true, "4quux": "garply"}}}]\n ]\n}',$=document.querySelector.bind(document),$$=document.querySelectorAll.bind(document),resultEl=$("#result"),pathEl=$("#path"),tryToJSON=t=>{try{resultEl.innerHTML=pathify(JSON.parse(t)),$("#error").innerText=""}catch(t){resultEl.innerHTML="",$("#error").innerText=t}},copyToClipboard=t=>{const e=document.createElement("textarea");e.textContent=t,document.body.appendChild(e),e.select(),document.execCommand("copy"),document.body.removeChild(e)},flashAlert=(t,e=2e3)=>{const a=document.createElement("div");a.textContent=t,a.classList.add("alert"),document.body.appendChild(a),setTimeout(()=>a.remove(),e)},handleClick=t=>{t.stopPropagation(),copyToClipboard(t.target.dataset.path),flashAlert("copied!"),$("#path-out").textContent=t.target.dataset.path},handleMouseOut=t=>{lastHighlighted.style.background="transparent",pathEl.style.display="none"},handleMouseOver=t=>{pathEl.textContent=t.target.dataset.path,pathEl.style.left=`${t.pageX+30}px`,pathEl.style.top=`${t.pageY}px`,pathEl.style.display="block",lastHighlighted.style.background="transparent",(lastHighlighted=t.target.closest("li")).style.background="#0ff"},handleNewJSON=t=>{tryToJSON(t.target.value),[...$$("#result *")].forEach(t=>{t.addEventListener("click",handleClick),t.addEventListener("mouseout",handleMouseOut),t.addEventListener("mouseover",handleMouseOver)})};$("textarea").addEventListener("change",handleNewJSON),$("textarea").addEventListener("keyup",handleNewJSON),$("textarea").value=defaultJSON,$("#brackets").addEventListener("change",t=>{bracketsOnly=!bracketsOnly,handleNewJSON({target:{value:$("textarea").value}})}),handleNewJSON({target:{value:defaultJSON}});
/**/ *{box-sizing:border-box;font-family:monospace;margin:0;padding:0}html{height:100%}#path-out{background-color:#0f0;padding:.3em}body{margin:0;height:100%;position:relative;background:#f8f8f8}textarea{width:100%;height:110px;resize:vertical}#opts{background:#e8e8e8;padding:.3em}#opts label{padding:.3em}#path{background:#000;transition:all 50ms;color:#fff;padding:.2em;position:absolute;display:none}#error{margin:.5em;color:red}#result ul{list-style:none}#result li{cursor:pointer;border-left:1em solid transparent}#result li:hover{border-color:#ff0}.alert{background:#f0f;padding:.2em;position:fixed;bottom:10px;right:10px}
<!-- --> <div class="wrapper"><textarea></textarea><div id="opts"><label>brackets only: <input id="brackets"type="checkbox"></label></div><div id="path-out">click a node to copy path to clipboard</div><div id="path"></div><div id="result"></div><div id="error"></div></div>
Unminified (also available on GitHub):
let bracketsOnly = false;
let lastHighlighted = {style: {}};
const keyToStr = k =>
!bracketsOnly && /^[a-zA-Z_$][a-zA-Z$_\d]*$/.test(k)
? `.${toHTML(k)}`
: `["${toHTML(k)}"]`
;
const pathToData = p => `data-path="data${p.join("")}"`;
const htmlSpecialChars = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
"\t": "\\t",
"\r": "\\r",
"\n": "\\n",
" ": " ",
};
const toHTML = x => ("" + x)
.replace(/[&<>"'\t\r\n ]/g, m => htmlSpecialChars[m])
;
const makeArray = (x, path) => `
[<ul ${pathToData(path)}>
${x.map((e, i) => {
path.push(`[${i}]`);
const html = `<li ${pathToData(path)}>
${pathify(e, path).trim()},
</li>`;
path.pop();
return html;
}).join("")}
</ul>]
`;
const makeObj = (x, path) => `
{<ul ${pathToData(path)}>
${Object.entries(x).map(([k, v]) => {
path.push(keyToStr(k));
const html = `<li ${pathToData(path)}>
"${toHTML(k)}": ${pathify(v, path).trim()},
</li>`;
path.pop();
return html;
}).join("")}
</ul>}
`;
const pathify = (x, path=[]) => {
if (Array.isArray(x)) {
return makeArray(x, path);
}
else if (typeof x === "object" && x !== null) {
return makeObj(x, path);
}
return toHTML(typeof x === "string" ? `"${x}"` : x);
};
const defaultJSON = `{
"corge": "test JSON... \\n asdf\\t asdf",
"foo-bar": [
{"id": 42},
[42, {"foo": {"baz": {"ba r<>!\\t": true, "4quux": "garply"}}}]
]
}`;
const $ = document.querySelector.bind(document);
const $$ = document.querySelectorAll.bind(document);
const resultEl = $("#result");
const pathEl = $("#path");
const tryToJSON = v => {
try {
resultEl.innerHTML = pathify(JSON.parse(v));
$("#error").innerText = "";
}
catch (err) {
resultEl.innerHTML = "";
$("#error").innerText = err;
}
};
const copyToClipboard = text => {
const ta = document.createElement("textarea");
ta.textContent = text;
document.body.appendChild(ta);
ta.select();
document.execCommand("copy");
document.body.removeChild(ta);
};
const flashAlert = (text, timeoutMS=2000) => {
const alert = document.createElement("div");
alert.textContent = text;
alert.classList.add("alert");
document.body.appendChild(alert);
setTimeout(() => alert.remove(), timeoutMS);
};
const handleClick = e => {
e.stopPropagation();
copyToClipboard(e.target.dataset.path);
flashAlert("copied!");
$("#path-out").textContent = e.target.dataset.path;
};
const handleMouseOut = e => {
lastHighlighted.style.background = "transparent";
pathEl.style.display = "none";
};
const handleMouseOver = e => {
pathEl.textContent = e.target.dataset.path;
pathEl.style.left = `${e.pageX + 30}px`;
pathEl.style.top = `${e.pageY}px`;
pathEl.style.display = "block";
lastHighlighted.style.background = "transparent";
lastHighlighted = e.target.closest("li");
lastHighlighted.style.background = "#0ff";
};
const handleNewJSON = e => {
tryToJSON(e.target.value);
[...$$("#result *")].forEach(e => {
e.addEventListener("click", handleClick);
e.addEventListener("mouseout", handleMouseOut);
e.addEventListener("mouseover", handleMouseOver);
});
};
$("textarea").addEventListener("change", handleNewJSON);
$("textarea").addEventListener("keyup", handleNewJSON);
$("textarea").value = defaultJSON;
$("#brackets").addEventListener("change", e => {
bracketsOnly = !bracketsOnly;
handleNewJSON({target: {value: $("textarea").value}});
});
handleNewJSON({target: {value: defaultJSON}});
* {
box-sizing: border-box;
font-family: monospace;
margin: 0;
padding: 0;
}
html {
height: 100%;
}
#path-out {
background-color: #0f0;
padding: 0.3em;
}
body {
margin: 0;
height: 100%;
position: relative;
background: #f8f8f8;
}
textarea {
width: 100%;
height: 110px;
resize: vertical;
}
#opts {
background: #e8e8e8;
padding: 0.3em;
}
#opts label {
padding: 0.3em;
}
#path {
background: black;
transition: all 0.05s;
color: white;
padding: 0.2em;
position: absolute;
display: none;
}
#error {
margin: 0.5em;
color: red;
}
#result ul {
list-style: none;
}
#result li {
cursor: pointer;
border-left: 1em solid transparent;
}
#result li:hover {
border-color: #ff0;
}
.alert {
background: #f0f;
padding: 0.2em;
position: fixed;
bottom: 10px;
right: 10px;
}
<div class="wrapper">
<textarea></textarea>
<div id="opts">
<label>
brackets only: <input id="brackets" type="checkbox">
</label>
</div>
<div id="path-out">click a node to copy path to clipboard</div>
<div id="path"></div>
<div id="result"></div>
<div id="error"></div>
</div>
This isn't intended as a substitute for learning how to fish but can save time once you do know.
// const path = 'info.value[0].item'
// const obj = { info: { value: [ { item: 'it works!' } ], randominfo: 3 } }
// getValue(path, obj)
export const getValue = ( path , obj) => {
const newPath = path.replace(/\]/g, "")
const arrayPath = newPath.split(/[\[\.]+/) || newPath;
const final = arrayPath.reduce( (obj, k) => obj ? obj[k] : obj, obj)
return final;
}
Here is an answer using object-scan.
When accessing a single entry, this answer doesn't really provide much benefit over vanilla javascript. However interacting with multiple fields at the same time this answer can be more performant.
Here is how you could interact with a single field
// const objectScan = require('object-scan');
const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] };
const get = (haystack, needle) => objectScan([needle], {
abort: true,
rtn: 'value'
})(haystack);
const set = (haystack, needle, value) => objectScan([needle], {
abort: true,
rtn: 'bool',
filterFn: ({ parent, property }) => {
parent[property] = value;
return true;
}
})(haystack);
console.log(get(data, 'items[1].name'));
// => bar
console.log(set(data, 'items[1].name', 'foo2'));
// => true
console.log(data);
// => { code: 42, items: [ { id: 1, name: 'foo' }, { id: 2, name: 'foo2' } ] }
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#13.8.0"></script>
Disclaimer: I'm the author of object-scan
and here is how you could interact with multiple fields at the same time
// const objectScan = require('object-scan');
const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] };
const get = (haystack, ...needles) => objectScan(needles, {
joined: true,
rtn: 'entry'
})(haystack);
const set = (haystack, actions) => objectScan(Object.keys(actions), {
rtn: 'count',
filterFn: ({ matchedBy, parent, property }) => {
matchedBy.forEach((m) => {
parent[property] = actions[m];
})
return true;
}
})(haystack);
console.log(get(data, 'items[0].name', 'items[1].name'));
// => [ [ 'items[1].name', 'bar' ], [ 'items[0].name', 'foo' ] ]
console.log(set(data, {
'items[0].name': 'foo1',
'items[1].name': 'foo2'
}));
// => 2
console.log(data);
// => { code: 42, items: [ { id: 1, name: 'foo1' }, { id: 2, name: 'foo2' } ] }
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#13.8.0"></script>
Disclaimer: I'm the author of object-scan
And here is how one could find an entity in a deeply nested object searching by id (as asked in comment)
// const objectScan = require('object-scan');
const myData = { 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' }] }] };
const findItemById = (haystack, id) => objectScan(['**(^items$).id'], {
abort: true,
useArraySelector: false,
rtn: 'parent',
filterFn: ({ value }) => value === id
})(haystack);
console.log(findItemById(myData, 5));
// => { id: 5, name: 'eee' }
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#13.8.0"></script>
Disclaimer: I'm the author of object-scan
what you need to do is really simple and it can be achieved trough recursivity:
const json_object = {
"item1":{
"name": "apple",
"value": 2,
},
"item2":{
"name": "pear",
"value": 4,
},
"item3":{
"name": "mango",
"value": 3,
"prices": {
"1": "9$",
"2": "59$",
"3": "1$"
}
}
}
function walkJson(json_object){
for(obj in json_object){
if(typeof json_object[obj] === 'string'){
console.log(`${obj}=>${json_object[obj]}`);
}else{
console.log(`${obj}=>${json_object[obj]}`);
walkJson(json_object[obj]);
}
}
}
walkJson(json_object);
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']}
]
My stringdata is coming from PHP file but still, I indicate here in var. When i directly take my json into obj it will nothing show thats why i put my json file as
var obj=JSON.parse(stringdata);
so after that i get message obj and show in alert box then I get data which is json array and store in one varible ArrObj then i read first object of that array with key value like this ArrObj[0].id
var stringdata={
"success": true,
"message": "working",
"data": [{
"id": 1,
"name": "foo"
}]
};
var obj=JSON.parse(stringdata);
var key = "message";
alert(obj[key]);
var keyobj = "data";
var ArrObj =obj[keyobj];
alert(ArrObj[0].id);
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?
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.
You can access it this way
data.items[1].name
or
data["items"][1]["name"]
Both ways are equal.
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
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.
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.
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.
It's simple explanation:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
/*
1. `data` is object contain `items` object*/
console.log(data);
/*
2. `items` object contain array of two objects as elements*/
console.log(data.items);
/*
3. you need 2nd element of array - the `1` from `[0, 1]`*/
console.log(data.items[1]);
/*
4. and you need value of `name` property of 2nd object-element of array)*/
console.log(data.items[1].name);
Here are 4 different methods mentioned to get the javascript object property:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
// Method 1
let method1 = data.items[1].name;
console.log(method1);
// Method 2
let method2 = data.items[1]["name"];
console.log(method2);
// Method 3
let method3 = data["items"][1]["name"];
console.log(method3);
// Method 4 Destructuring
let { items: [, { name: second_name }] } = data;
console.log(second_name);
You could use lodash _get function:
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.get(object, 'a[0].b.c');
// => 3
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.
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/
Another more useful document depicting the situation above:
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Basics#Bracket_notation
Property access via dot walking: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#Dot_notation
Accessing dynamically multi levels object.
var obj = {
name: "john doe",
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/
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.
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");
I prefer JQuery. It's cleaner and easy to read.
$.each($.parseJSON(data), function (key, value) {
alert(value.<propertyname>);
});
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 firstand firstOrDefaultrespectively. 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
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);
}
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.
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>
In 2020, you can use #babel/plugin-proposal-optional-chaining it is very easy to access nested values in an object.
const obj = {
foo: {
bar: {
baz: class {
},
},
},
};
const baz = new obj?.foo?.bar?.baz(); // baz instance
const safe = new obj?.qux?.baz(); // undefined
const safe2 = new obj?.foo.bar.qux?.(); // undefined
https://babeljs.io/docs/en/babel-plugin-proposal-optional-chaining
https://github.com/tc39/proposal-optional-chaining
Dynamic approach
In below deep(data,key) function, you can use arbitrary key string - in your case items[1].name (you can use array notation [i] at any level) - if key is invalid then undefined is return.
let deep = (o,k) => k.split('.').reduce((a,c,i) => {
let m=c.match(/(.*?)\[(\d*)\]/);
if(m && a!=null && a[m[1]]!=null) return a[m[1]][+m[2]];
return a==null ? a: a[c];
},o);
// TEST
let key = 'items[1].name' // arbitrary deep-key
let data = {
code: 42,
items: [{ id: 11, name: 'foo'}, { id: 22, name: 'bar'},]
};
console.log( key,'=', deep(data,key) );
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>
You can use the syntax jsonObject.key to access the the value. And if you want access a value from an array, then you can use the syntax jsonObjectArray[index].key.
Here are the code examples to access various values to give you the idea.
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
// if you want 'bar'
console.log(data.items[1].name);
// if you want array of item names
console.log(data.items.map(x => x.name));
// get the id of the item where name = 'bar'
console.log(data.items.filter(x => (x.name == "bar") ? x.id : null)[0].id);
this is how i have done this.
let groups = [
{
id:1,
title:"Group 1",
members:[
{
id:1,
name:"Aftab",
battry:'10%'
},
{
id:2,
name:"Jamal",
},
{
id:3,
name:"Hamid",
},
{
id:4,
name:"Aqeel",
},
]
},
{
id:2,
title:"Group 2",
members:[
{
id:1,
name:"Aftab",
battry:'10%'
},
{
id:2,
name:"Jamal",
battry:'10%'
},
{
id:3,
name:"Hamid",
},
]
},
{
id:3,
title:"Group 3",
members:[
{
id:1,
name:"Aftab",
battry:'10%'
},
{
id:3,
name:"Hamid",
},
{
id:4,
name:"Aqeel",
},
]
}
]
groups.map((item) => {
// if(item.id == 2){
item.members.map((element) => {
if(element.id == 1){
element.battry="20%"
}
})
//}
})
groups.forEach((item) => {
item.members.forEach((item) => {
console.log(item)
})
})
If you're trying to find a path in a JSON string, you can dump your data into https://jsonpathfinder.com and click on the GUI elements. It'll generate the JS syntax for the path to the element.
Beyond that, for any arrays you might want to iterate, replace the relevant array offset indices like [0] with a loop.
Here's a simpler version of the tool you can run here, or at https://ggorlen.github.io/json-dive/. Click the node you want to copy the path to your clipboard.
/* code minified to make the tool easier to run without having to scroll */ let bracketsOnly=!1,lastHighlighted={style:{}};const keyToStr=t=>!bracketsOnly&&/^[a-zA-Z_$][a-zA-Z$_\d]*$/.test(t)?`.${toHTML(t)}`:`["${toHTML(t)}"]`,pathToData=t=>`data-path="data${t.join("")}"`,htmlSpecialChars={"&":"&","<":"<",">":">",'"':""","'":"'","\t":"\\t","\r":"\\r","\n":"\\n"," ":" "},toHTML=t=>(""+t).replace(/[&<>"'\t\r\n ]/g,t=>htmlSpecialChars[t]),makeArray=(t,e)=>`\n [<ul ${pathToData(e)}>\n ${t.map((t,a)=>{e.push(`[${a}]`);const n=`<li ${pathToData(e)}>\n ${pathify(t,e).trim()},\n </li>`;return e.pop(),n}).join("")}\n </ul>]\n`,makeObj=(t,e)=>`\n {<ul ${pathToData(e)}>\n ${Object.entries(t).map(([t,a])=>{e.push(keyToStr(t));const n=`<li ${pathToData(e)}>\n "${toHTML(t)}": ${pathify(a,e).trim()},\n </li>`;return e.pop(),n}).join("")}\n </ul>}\n`,pathify=(t,e=[])=>Array.isArray(t)?makeArray(t,e):"object"==typeof t&&t!=null?makeObj(t,e):toHTML("string"==typeof t?`"${t}"`:t),defaultJSON='{\n "corge": "test JSON... \\n asdf\\t asdf",\n "foo-bar": [\n {"id": 42},\n [42, {"foo": {"baz": {"ba r<>!\\t": true, "4quux": "garply"}}}]\n ]\n}',$=document.querySelector.bind(document),$$=document.querySelectorAll.bind(document),resultEl=$("#result"),pathEl=$("#path"),tryToJSON=t=>{try{resultEl.innerHTML=pathify(JSON.parse(t)),$("#error").innerText=""}catch(t){resultEl.innerHTML="",$("#error").innerText=t}},copyToClipboard=t=>{const e=document.createElement("textarea");e.textContent=t,document.body.appendChild(e),e.select(),document.execCommand("copy"),document.body.removeChild(e)},flashAlert=(t,e=2e3)=>{const a=document.createElement("div");a.textContent=t,a.classList.add("alert"),document.body.appendChild(a),setTimeout(()=>a.remove(),e)},handleClick=t=>{t.stopPropagation(),copyToClipboard(t.target.dataset.path),flashAlert("copied!"),$("#path-out").textContent=t.target.dataset.path},handleMouseOut=t=>{lastHighlighted.style.background="transparent",pathEl.style.display="none"},handleMouseOver=t=>{pathEl.textContent=t.target.dataset.path,pathEl.style.left=`${t.pageX+30}px`,pathEl.style.top=`${t.pageY}px`,pathEl.style.display="block",lastHighlighted.style.background="transparent",(lastHighlighted=t.target.closest("li")).style.background="#0ff"},handleNewJSON=t=>{tryToJSON(t.target.value),[...$$("#result *")].forEach(t=>{t.addEventListener("click",handleClick),t.addEventListener("mouseout",handleMouseOut),t.addEventListener("mouseover",handleMouseOver)})};$("textarea").addEventListener("change",handleNewJSON),$("textarea").addEventListener("keyup",handleNewJSON),$("textarea").value=defaultJSON,$("#brackets").addEventListener("change",t=>{bracketsOnly=!bracketsOnly,handleNewJSON({target:{value:$("textarea").value}})}),handleNewJSON({target:{value:defaultJSON}});
/**/ *{box-sizing:border-box;font-family:monospace;margin:0;padding:0}html{height:100%}#path-out{background-color:#0f0;padding:.3em}body{margin:0;height:100%;position:relative;background:#f8f8f8}textarea{width:100%;height:110px;resize:vertical}#opts{background:#e8e8e8;padding:.3em}#opts label{padding:.3em}#path{background:#000;transition:all 50ms;color:#fff;padding:.2em;position:absolute;display:none}#error{margin:.5em;color:red}#result ul{list-style:none}#result li{cursor:pointer;border-left:1em solid transparent}#result li:hover{border-color:#ff0}.alert{background:#f0f;padding:.2em;position:fixed;bottom:10px;right:10px}
<!-- --> <div class="wrapper"><textarea></textarea><div id="opts"><label>brackets only: <input id="brackets"type="checkbox"></label></div><div id="path-out">click a node to copy path to clipboard</div><div id="path"></div><div id="result"></div><div id="error"></div></div>
Unminified (also available on GitHub):
let bracketsOnly = false;
let lastHighlighted = {style: {}};
const keyToStr = k =>
!bracketsOnly && /^[a-zA-Z_$][a-zA-Z$_\d]*$/.test(k)
? `.${toHTML(k)}`
: `["${toHTML(k)}"]`
;
const pathToData = p => `data-path="data${p.join("")}"`;
const htmlSpecialChars = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
"\t": "\\t",
"\r": "\\r",
"\n": "\\n",
" ": " ",
};
const toHTML = x => ("" + x)
.replace(/[&<>"'\t\r\n ]/g, m => htmlSpecialChars[m])
;
const makeArray = (x, path) => `
[<ul ${pathToData(path)}>
${x.map((e, i) => {
path.push(`[${i}]`);
const html = `<li ${pathToData(path)}>
${pathify(e, path).trim()},
</li>`;
path.pop();
return html;
}).join("")}
</ul>]
`;
const makeObj = (x, path) => `
{<ul ${pathToData(path)}>
${Object.entries(x).map(([k, v]) => {
path.push(keyToStr(k));
const html = `<li ${pathToData(path)}>
"${toHTML(k)}": ${pathify(v, path).trim()},
</li>`;
path.pop();
return html;
}).join("")}
</ul>}
`;
const pathify = (x, path=[]) => {
if (Array.isArray(x)) {
return makeArray(x, path);
}
else if (typeof x === "object" && x !== null) {
return makeObj(x, path);
}
return toHTML(typeof x === "string" ? `"${x}"` : x);
};
const defaultJSON = `{
"corge": "test JSON... \\n asdf\\t asdf",
"foo-bar": [
{"id": 42},
[42, {"foo": {"baz": {"ba r<>!\\t": true, "4quux": "garply"}}}]
]
}`;
const $ = document.querySelector.bind(document);
const $$ = document.querySelectorAll.bind(document);
const resultEl = $("#result");
const pathEl = $("#path");
const tryToJSON = v => {
try {
resultEl.innerHTML = pathify(JSON.parse(v));
$("#error").innerText = "";
}
catch (err) {
resultEl.innerHTML = "";
$("#error").innerText = err;
}
};
const copyToClipboard = text => {
const ta = document.createElement("textarea");
ta.textContent = text;
document.body.appendChild(ta);
ta.select();
document.execCommand("copy");
document.body.removeChild(ta);
};
const flashAlert = (text, timeoutMS=2000) => {
const alert = document.createElement("div");
alert.textContent = text;
alert.classList.add("alert");
document.body.appendChild(alert);
setTimeout(() => alert.remove(), timeoutMS);
};
const handleClick = e => {
e.stopPropagation();
copyToClipboard(e.target.dataset.path);
flashAlert("copied!");
$("#path-out").textContent = e.target.dataset.path;
};
const handleMouseOut = e => {
lastHighlighted.style.background = "transparent";
pathEl.style.display = "none";
};
const handleMouseOver = e => {
pathEl.textContent = e.target.dataset.path;
pathEl.style.left = `${e.pageX + 30}px`;
pathEl.style.top = `${e.pageY}px`;
pathEl.style.display = "block";
lastHighlighted.style.background = "transparent";
lastHighlighted = e.target.closest("li");
lastHighlighted.style.background = "#0ff";
};
const handleNewJSON = e => {
tryToJSON(e.target.value);
[...$$("#result *")].forEach(e => {
e.addEventListener("click", handleClick);
e.addEventListener("mouseout", handleMouseOut);
e.addEventListener("mouseover", handleMouseOver);
});
};
$("textarea").addEventListener("change", handleNewJSON);
$("textarea").addEventListener("keyup", handleNewJSON);
$("textarea").value = defaultJSON;
$("#brackets").addEventListener("change", e => {
bracketsOnly = !bracketsOnly;
handleNewJSON({target: {value: $("textarea").value}});
});
handleNewJSON({target: {value: defaultJSON}});
* {
box-sizing: border-box;
font-family: monospace;
margin: 0;
padding: 0;
}
html {
height: 100%;
}
#path-out {
background-color: #0f0;
padding: 0.3em;
}
body {
margin: 0;
height: 100%;
position: relative;
background: #f8f8f8;
}
textarea {
width: 100%;
height: 110px;
resize: vertical;
}
#opts {
background: #e8e8e8;
padding: 0.3em;
}
#opts label {
padding: 0.3em;
}
#path {
background: black;
transition: all 0.05s;
color: white;
padding: 0.2em;
position: absolute;
display: none;
}
#error {
margin: 0.5em;
color: red;
}
#result ul {
list-style: none;
}
#result li {
cursor: pointer;
border-left: 1em solid transparent;
}
#result li:hover {
border-color: #ff0;
}
.alert {
background: #f0f;
padding: 0.2em;
position: fixed;
bottom: 10px;
right: 10px;
}
<div class="wrapper">
<textarea></textarea>
<div id="opts">
<label>
brackets only: <input id="brackets" type="checkbox">
</label>
</div>
<div id="path-out">click a node to copy path to clipboard</div>
<div id="path"></div>
<div id="result"></div>
<div id="error"></div>
</div>
This isn't intended as a substitute for learning how to fish but can save time once you do know.
// const path = 'info.value[0].item'
// const obj = { info: { value: [ { item: 'it works!' } ], randominfo: 3 } }
// getValue(path, obj)
export const getValue = ( path , obj) => {
const newPath = path.replace(/\]/g, "")
const arrayPath = newPath.split(/[\[\.]+/) || newPath;
const final = arrayPath.reduce( (obj, k) => obj ? obj[k] : obj, obj)
return final;
}
Here is an answer using object-scan.
When accessing a single entry, this answer doesn't really provide much benefit over vanilla javascript. However interacting with multiple fields at the same time this answer can be more performant.
Here is how you could interact with a single field
// const objectScan = require('object-scan');
const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] };
const get = (haystack, needle) => objectScan([needle], {
abort: true,
rtn: 'value'
})(haystack);
const set = (haystack, needle, value) => objectScan([needle], {
abort: true,
rtn: 'bool',
filterFn: ({ parent, property }) => {
parent[property] = value;
return true;
}
})(haystack);
console.log(get(data, 'items[1].name'));
// => bar
console.log(set(data, 'items[1].name', 'foo2'));
// => true
console.log(data);
// => { code: 42, items: [ { id: 1, name: 'foo' }, { id: 2, name: 'foo2' } ] }
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#13.8.0"></script>
Disclaimer: I'm the author of object-scan
and here is how you could interact with multiple fields at the same time
// const objectScan = require('object-scan');
const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] };
const get = (haystack, ...needles) => objectScan(needles, {
joined: true,
rtn: 'entry'
})(haystack);
const set = (haystack, actions) => objectScan(Object.keys(actions), {
rtn: 'count',
filterFn: ({ matchedBy, parent, property }) => {
matchedBy.forEach((m) => {
parent[property] = actions[m];
})
return true;
}
})(haystack);
console.log(get(data, 'items[0].name', 'items[1].name'));
// => [ [ 'items[1].name', 'bar' ], [ 'items[0].name', 'foo' ] ]
console.log(set(data, {
'items[0].name': 'foo1',
'items[1].name': 'foo2'
}));
// => 2
console.log(data);
// => { code: 42, items: [ { id: 1, name: 'foo1' }, { id: 2, name: 'foo2' } ] }
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#13.8.0"></script>
Disclaimer: I'm the author of object-scan
And here is how one could find an entity in a deeply nested object searching by id (as asked in comment)
// const objectScan = require('object-scan');
const myData = { 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' }] }] };
const findItemById = (haystack, id) => objectScan(['**(^items$).id'], {
abort: true,
useArraySelector: false,
rtn: 'parent',
filterFn: ({ value }) => value === id
})(haystack);
console.log(findItemById(myData, 5));
// => { id: 5, name: 'eee' }
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#13.8.0"></script>
Disclaimer: I'm the author of object-scan
what you need to do is really simple and it can be achieved trough recursivity:
const json_object = {
"item1":{
"name": "apple",
"value": 2,
},
"item2":{
"name": "pear",
"value": 4,
},
"item3":{
"name": "mango",
"value": 3,
"prices": {
"1": "9$",
"2": "59$",
"3": "1$"
}
}
}
function walkJson(json_object){
for(obj in json_object){
if(typeof json_object[obj] === 'string'){
console.log(`${obj}=>${json_object[obj]}`);
}else{
console.log(`${obj}=>${json_object[obj]}`);
walkJson(json_object[obj]);
}
}
}
walkJson(json_object);
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']}
]
My stringdata is coming from PHP file but still, I indicate here in var. When i directly take my json into obj it will nothing show thats why i put my json file as
var obj=JSON.parse(stringdata);
so after that i get message obj and show in alert box then I get data which is json array and store in one varible ArrObj then i read first object of that array with key value like this ArrObj[0].id
var stringdata={
"success": true,
"message": "working",
"data": [{
"id": 1,
"name": "foo"
}]
};
var obj=JSON.parse(stringdata);
var key = "message";
alert(obj[key]);
var keyobj = "data";
var ArrObj =obj[keyobj];
alert(ArrObj[0].id);
I want to make a cool higher-order function chain for what I could do (perhaps more verbosely) like this:
for (var idx = 0; idx < collecionA.length; idx++) {
for (item in collectionA[idx].children) {
if (item.sku == "someVal") return idx
}
}
Does anyone see a snazzy way to do this with map/find/filter/reduce etc.? I keep wanting to use forEach but then get pwnd when I realize I can't return from it.
Something like:
return collectionA.children.findIndex( (child) => child.children.oneOfThemIncludesAnObjectWithThisProperty("someVal"))
Use Array.findIndex() on the outer collection. For each item, iterate the children with Array.some(), and check if the value of the property (sku) matches the requested value. As soon as a matching value is found, some returns true immediately, and findIndex returns the current index.
const collection = [{"children":[{"sku":"someOtherVal"}]},{"children":[{"sku":"someVal"}]},{"children":[{"sku":"someOtherVal"}]}];
const findIndexWithChildProp = (arr, prop, val) =>
arr.findIndex(({ children }) =>
children.some(({ [prop]: v }) => v === val));
const result = findIndexWithChildProp(collection, 'sku', 'someVal');
console.log(result);
This could be what you are looking for:
function func() {
var index = -1;
collectionA.forEach((p, i) => p.children.forEach(item => {
if (item.sku == "someVal") index = i;
}));
return index;
}
var collectionA = [{
children: [{
sku: "someOtherVal"
}]
}, {
children: [{
sku: "someVal"
}]
}, {
children: [{
sku: "someOtherVal"
}]
}]
console.log(func());
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?
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.
You can access it this way
data.items[1].name
or
data["items"][1]["name"]
Both ways are equal.
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
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.
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.
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.
It's simple explanation:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
/*
1. `data` is object contain `items` object*/
console.log(data);
/*
2. `items` object contain array of two objects as elements*/
console.log(data.items);
/*
3. you need 2nd element of array - the `1` from `[0, 1]`*/
console.log(data.items[1]);
/*
4. and you need value of `name` property of 2nd object-element of array)*/
console.log(data.items[1].name);
Here are 4 different methods mentioned to get the javascript object property:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
// Method 1
let method1 = data.items[1].name;
console.log(method1);
// Method 2
let method2 = data.items[1]["name"];
console.log(method2);
// Method 3
let method3 = data["items"][1]["name"];
console.log(method3);
// Method 4 Destructuring
let { items: [, { name: second_name }] } = data;
console.log(second_name);
You could use lodash _get function:
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.get(object, 'a[0].b.c');
// => 3
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.
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/
Another more useful document depicting the situation above:
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Basics#Bracket_notation
Property access via dot walking: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#Dot_notation
Accessing dynamically multi levels object.
var obj = {
name: "john doe",
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/
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.
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");
I prefer JQuery. It's cleaner and easy to read.
$.each($.parseJSON(data), function (key, value) {
alert(value.<propertyname>);
});
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 firstand firstOrDefaultrespectively. 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
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);
}
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.
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>
In 2020, you can use #babel/plugin-proposal-optional-chaining it is very easy to access nested values in an object.
const obj = {
foo: {
bar: {
baz: class {
},
},
},
};
const baz = new obj?.foo?.bar?.baz(); // baz instance
const safe = new obj?.qux?.baz(); // undefined
const safe2 = new obj?.foo.bar.qux?.(); // undefined
https://babeljs.io/docs/en/babel-plugin-proposal-optional-chaining
https://github.com/tc39/proposal-optional-chaining
Dynamic approach
In below deep(data,key) function, you can use arbitrary key string - in your case items[1].name (you can use array notation [i] at any level) - if key is invalid then undefined is return.
let deep = (o,k) => k.split('.').reduce((a,c,i) => {
let m=c.match(/(.*?)\[(\d*)\]/);
if(m && a!=null && a[m[1]]!=null) return a[m[1]][+m[2]];
return a==null ? a: a[c];
},o);
// TEST
let key = 'items[1].name' // arbitrary deep-key
let data = {
code: 42,
items: [{ id: 11, name: 'foo'}, { id: 22, name: 'bar'},]
};
console.log( key,'=', deep(data,key) );
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>
You can use the syntax jsonObject.key to access the the value. And if you want access a value from an array, then you can use the syntax jsonObjectArray[index].key.
Here are the code examples to access various values to give you the idea.
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
// if you want 'bar'
console.log(data.items[1].name);
// if you want array of item names
console.log(data.items.map(x => x.name));
// get the id of the item where name = 'bar'
console.log(data.items.filter(x => (x.name == "bar") ? x.id : null)[0].id);
this is how i have done this.
let groups = [
{
id:1,
title:"Group 1",
members:[
{
id:1,
name:"Aftab",
battry:'10%'
},
{
id:2,
name:"Jamal",
},
{
id:3,
name:"Hamid",
},
{
id:4,
name:"Aqeel",
},
]
},
{
id:2,
title:"Group 2",
members:[
{
id:1,
name:"Aftab",
battry:'10%'
},
{
id:2,
name:"Jamal",
battry:'10%'
},
{
id:3,
name:"Hamid",
},
]
},
{
id:3,
title:"Group 3",
members:[
{
id:1,
name:"Aftab",
battry:'10%'
},
{
id:3,
name:"Hamid",
},
{
id:4,
name:"Aqeel",
},
]
}
]
groups.map((item) => {
// if(item.id == 2){
item.members.map((element) => {
if(element.id == 1){
element.battry="20%"
}
})
//}
})
groups.forEach((item) => {
item.members.forEach((item) => {
console.log(item)
})
})
If you're trying to find a path in a JSON string, you can dump your data into https://jsonpathfinder.com and click on the GUI elements. It'll generate the JS syntax for the path to the element.
Beyond that, for any arrays you might want to iterate, replace the relevant array offset indices like [0] with a loop.
Here's a simpler version of the tool you can run here, or at https://ggorlen.github.io/json-dive/. Click the node you want to copy the path to your clipboard.
/* code minified to make the tool easier to run without having to scroll */ let bracketsOnly=!1,lastHighlighted={style:{}};const keyToStr=t=>!bracketsOnly&&/^[a-zA-Z_$][a-zA-Z$_\d]*$/.test(t)?`.${toHTML(t)}`:`["${toHTML(t)}"]`,pathToData=t=>`data-path="data${t.join("")}"`,htmlSpecialChars={"&":"&","<":"<",">":">",'"':""","'":"'","\t":"\\t","\r":"\\r","\n":"\\n"," ":" "},toHTML=t=>(""+t).replace(/[&<>"'\t\r\n ]/g,t=>htmlSpecialChars[t]),makeArray=(t,e)=>`\n [<ul ${pathToData(e)}>\n ${t.map((t,a)=>{e.push(`[${a}]`);const n=`<li ${pathToData(e)}>\n ${pathify(t,e).trim()},\n </li>`;return e.pop(),n}).join("")}\n </ul>]\n`,makeObj=(t,e)=>`\n {<ul ${pathToData(e)}>\n ${Object.entries(t).map(([t,a])=>{e.push(keyToStr(t));const n=`<li ${pathToData(e)}>\n "${toHTML(t)}": ${pathify(a,e).trim()},\n </li>`;return e.pop(),n}).join("")}\n </ul>}\n`,pathify=(t,e=[])=>Array.isArray(t)?makeArray(t,e):"object"==typeof t&&t!=null?makeObj(t,e):toHTML("string"==typeof t?`"${t}"`:t),defaultJSON='{\n "corge": "test JSON... \\n asdf\\t asdf",\n "foo-bar": [\n {"id": 42},\n [42, {"foo": {"baz": {"ba r<>!\\t": true, "4quux": "garply"}}}]\n ]\n}',$=document.querySelector.bind(document),$$=document.querySelectorAll.bind(document),resultEl=$("#result"),pathEl=$("#path"),tryToJSON=t=>{try{resultEl.innerHTML=pathify(JSON.parse(t)),$("#error").innerText=""}catch(t){resultEl.innerHTML="",$("#error").innerText=t}},copyToClipboard=t=>{const e=document.createElement("textarea");e.textContent=t,document.body.appendChild(e),e.select(),document.execCommand("copy"),document.body.removeChild(e)},flashAlert=(t,e=2e3)=>{const a=document.createElement("div");a.textContent=t,a.classList.add("alert"),document.body.appendChild(a),setTimeout(()=>a.remove(),e)},handleClick=t=>{t.stopPropagation(),copyToClipboard(t.target.dataset.path),flashAlert("copied!"),$("#path-out").textContent=t.target.dataset.path},handleMouseOut=t=>{lastHighlighted.style.background="transparent",pathEl.style.display="none"},handleMouseOver=t=>{pathEl.textContent=t.target.dataset.path,pathEl.style.left=`${t.pageX+30}px`,pathEl.style.top=`${t.pageY}px`,pathEl.style.display="block",lastHighlighted.style.background="transparent",(lastHighlighted=t.target.closest("li")).style.background="#0ff"},handleNewJSON=t=>{tryToJSON(t.target.value),[...$$("#result *")].forEach(t=>{t.addEventListener("click",handleClick),t.addEventListener("mouseout",handleMouseOut),t.addEventListener("mouseover",handleMouseOver)})};$("textarea").addEventListener("change",handleNewJSON),$("textarea").addEventListener("keyup",handleNewJSON),$("textarea").value=defaultJSON,$("#brackets").addEventListener("change",t=>{bracketsOnly=!bracketsOnly,handleNewJSON({target:{value:$("textarea").value}})}),handleNewJSON({target:{value:defaultJSON}});
/**/ *{box-sizing:border-box;font-family:monospace;margin:0;padding:0}html{height:100%}#path-out{background-color:#0f0;padding:.3em}body{margin:0;height:100%;position:relative;background:#f8f8f8}textarea{width:100%;height:110px;resize:vertical}#opts{background:#e8e8e8;padding:.3em}#opts label{padding:.3em}#path{background:#000;transition:all 50ms;color:#fff;padding:.2em;position:absolute;display:none}#error{margin:.5em;color:red}#result ul{list-style:none}#result li{cursor:pointer;border-left:1em solid transparent}#result li:hover{border-color:#ff0}.alert{background:#f0f;padding:.2em;position:fixed;bottom:10px;right:10px}
<!-- --> <div class="wrapper"><textarea></textarea><div id="opts"><label>brackets only: <input id="brackets"type="checkbox"></label></div><div id="path-out">click a node to copy path to clipboard</div><div id="path"></div><div id="result"></div><div id="error"></div></div>
Unminified (also available on GitHub):
let bracketsOnly = false;
let lastHighlighted = {style: {}};
const keyToStr = k =>
!bracketsOnly && /^[a-zA-Z_$][a-zA-Z$_\d]*$/.test(k)
? `.${toHTML(k)}`
: `["${toHTML(k)}"]`
;
const pathToData = p => `data-path="data${p.join("")}"`;
const htmlSpecialChars = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
"\t": "\\t",
"\r": "\\r",
"\n": "\\n",
" ": " ",
};
const toHTML = x => ("" + x)
.replace(/[&<>"'\t\r\n ]/g, m => htmlSpecialChars[m])
;
const makeArray = (x, path) => `
[<ul ${pathToData(path)}>
${x.map((e, i) => {
path.push(`[${i}]`);
const html = `<li ${pathToData(path)}>
${pathify(e, path).trim()},
</li>`;
path.pop();
return html;
}).join("")}
</ul>]
`;
const makeObj = (x, path) => `
{<ul ${pathToData(path)}>
${Object.entries(x).map(([k, v]) => {
path.push(keyToStr(k));
const html = `<li ${pathToData(path)}>
"${toHTML(k)}": ${pathify(v, path).trim()},
</li>`;
path.pop();
return html;
}).join("")}
</ul>}
`;
const pathify = (x, path=[]) => {
if (Array.isArray(x)) {
return makeArray(x, path);
}
else if (typeof x === "object" && x !== null) {
return makeObj(x, path);
}
return toHTML(typeof x === "string" ? `"${x}"` : x);
};
const defaultJSON = `{
"corge": "test JSON... \\n asdf\\t asdf",
"foo-bar": [
{"id": 42},
[42, {"foo": {"baz": {"ba r<>!\\t": true, "4quux": "garply"}}}]
]
}`;
const $ = document.querySelector.bind(document);
const $$ = document.querySelectorAll.bind(document);
const resultEl = $("#result");
const pathEl = $("#path");
const tryToJSON = v => {
try {
resultEl.innerHTML = pathify(JSON.parse(v));
$("#error").innerText = "";
}
catch (err) {
resultEl.innerHTML = "";
$("#error").innerText = err;
}
};
const copyToClipboard = text => {
const ta = document.createElement("textarea");
ta.textContent = text;
document.body.appendChild(ta);
ta.select();
document.execCommand("copy");
document.body.removeChild(ta);
};
const flashAlert = (text, timeoutMS=2000) => {
const alert = document.createElement("div");
alert.textContent = text;
alert.classList.add("alert");
document.body.appendChild(alert);
setTimeout(() => alert.remove(), timeoutMS);
};
const handleClick = e => {
e.stopPropagation();
copyToClipboard(e.target.dataset.path);
flashAlert("copied!");
$("#path-out").textContent = e.target.dataset.path;
};
const handleMouseOut = e => {
lastHighlighted.style.background = "transparent";
pathEl.style.display = "none";
};
const handleMouseOver = e => {
pathEl.textContent = e.target.dataset.path;
pathEl.style.left = `${e.pageX + 30}px`;
pathEl.style.top = `${e.pageY}px`;
pathEl.style.display = "block";
lastHighlighted.style.background = "transparent";
lastHighlighted = e.target.closest("li");
lastHighlighted.style.background = "#0ff";
};
const handleNewJSON = e => {
tryToJSON(e.target.value);
[...$$("#result *")].forEach(e => {
e.addEventListener("click", handleClick);
e.addEventListener("mouseout", handleMouseOut);
e.addEventListener("mouseover", handleMouseOver);
});
};
$("textarea").addEventListener("change", handleNewJSON);
$("textarea").addEventListener("keyup", handleNewJSON);
$("textarea").value = defaultJSON;
$("#brackets").addEventListener("change", e => {
bracketsOnly = !bracketsOnly;
handleNewJSON({target: {value: $("textarea").value}});
});
handleNewJSON({target: {value: defaultJSON}});
* {
box-sizing: border-box;
font-family: monospace;
margin: 0;
padding: 0;
}
html {
height: 100%;
}
#path-out {
background-color: #0f0;
padding: 0.3em;
}
body {
margin: 0;
height: 100%;
position: relative;
background: #f8f8f8;
}
textarea {
width: 100%;
height: 110px;
resize: vertical;
}
#opts {
background: #e8e8e8;
padding: 0.3em;
}
#opts label {
padding: 0.3em;
}
#path {
background: black;
transition: all 0.05s;
color: white;
padding: 0.2em;
position: absolute;
display: none;
}
#error {
margin: 0.5em;
color: red;
}
#result ul {
list-style: none;
}
#result li {
cursor: pointer;
border-left: 1em solid transparent;
}
#result li:hover {
border-color: #ff0;
}
.alert {
background: #f0f;
padding: 0.2em;
position: fixed;
bottom: 10px;
right: 10px;
}
<div class="wrapper">
<textarea></textarea>
<div id="opts">
<label>
brackets only: <input id="brackets" type="checkbox">
</label>
</div>
<div id="path-out">click a node to copy path to clipboard</div>
<div id="path"></div>
<div id="result"></div>
<div id="error"></div>
</div>
This isn't intended as a substitute for learning how to fish but can save time once you do know.
// const path = 'info.value[0].item'
// const obj = { info: { value: [ { item: 'it works!' } ], randominfo: 3 } }
// getValue(path, obj)
export const getValue = ( path , obj) => {
const newPath = path.replace(/\]/g, "")
const arrayPath = newPath.split(/[\[\.]+/) || newPath;
const final = arrayPath.reduce( (obj, k) => obj ? obj[k] : obj, obj)
return final;
}
Here is an answer using object-scan.
When accessing a single entry, this answer doesn't really provide much benefit over vanilla javascript. However interacting with multiple fields at the same time this answer can be more performant.
Here is how you could interact with a single field
// const objectScan = require('object-scan');
const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] };
const get = (haystack, needle) => objectScan([needle], {
abort: true,
rtn: 'value'
})(haystack);
const set = (haystack, needle, value) => objectScan([needle], {
abort: true,
rtn: 'bool',
filterFn: ({ parent, property }) => {
parent[property] = value;
return true;
}
})(haystack);
console.log(get(data, 'items[1].name'));
// => bar
console.log(set(data, 'items[1].name', 'foo2'));
// => true
console.log(data);
// => { code: 42, items: [ { id: 1, name: 'foo' }, { id: 2, name: 'foo2' } ] }
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#13.8.0"></script>
Disclaimer: I'm the author of object-scan
and here is how you could interact with multiple fields at the same time
// const objectScan = require('object-scan');
const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] };
const get = (haystack, ...needles) => objectScan(needles, {
joined: true,
rtn: 'entry'
})(haystack);
const set = (haystack, actions) => objectScan(Object.keys(actions), {
rtn: 'count',
filterFn: ({ matchedBy, parent, property }) => {
matchedBy.forEach((m) => {
parent[property] = actions[m];
})
return true;
}
})(haystack);
console.log(get(data, 'items[0].name', 'items[1].name'));
// => [ [ 'items[1].name', 'bar' ], [ 'items[0].name', 'foo' ] ]
console.log(set(data, {
'items[0].name': 'foo1',
'items[1].name': 'foo2'
}));
// => 2
console.log(data);
// => { code: 42, items: [ { id: 1, name: 'foo1' }, { id: 2, name: 'foo2' } ] }
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#13.8.0"></script>
Disclaimer: I'm the author of object-scan
And here is how one could find an entity in a deeply nested object searching by id (as asked in comment)
// const objectScan = require('object-scan');
const myData = { 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' }] }] };
const findItemById = (haystack, id) => objectScan(['**(^items$).id'], {
abort: true,
useArraySelector: false,
rtn: 'parent',
filterFn: ({ value }) => value === id
})(haystack);
console.log(findItemById(myData, 5));
// => { id: 5, name: 'eee' }
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#13.8.0"></script>
Disclaimer: I'm the author of object-scan
what you need to do is really simple and it can be achieved trough recursivity:
const json_object = {
"item1":{
"name": "apple",
"value": 2,
},
"item2":{
"name": "pear",
"value": 4,
},
"item3":{
"name": "mango",
"value": 3,
"prices": {
"1": "9$",
"2": "59$",
"3": "1$"
}
}
}
function walkJson(json_object){
for(obj in json_object){
if(typeof json_object[obj] === 'string'){
console.log(`${obj}=>${json_object[obj]}`);
}else{
console.log(`${obj}=>${json_object[obj]}`);
walkJson(json_object[obj]);
}
}
}
walkJson(json_object);
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']}
]
My stringdata is coming from PHP file but still, I indicate here in var. When i directly take my json into obj it will nothing show thats why i put my json file as
var obj=JSON.parse(stringdata);
so after that i get message obj and show in alert box then I get data which is json array and store in one varible ArrObj then i read first object of that array with key value like this ArrObj[0].id
var stringdata={
"success": true,
"message": "working",
"data": [{
"id": 1,
"name": "foo"
}]
};
var obj=JSON.parse(stringdata);
var key = "message";
alert(obj[key]);
var keyobj = "data";
var ArrObj =obj[keyobj];
alert(ArrObj[0].id);