I\'d like to traverse a JSON object tree, but cannot find any library for that. It doesn\'t seem difficult but it feels like reinventing the wheel.
In XML there are
There's a new library for traversing JSON data with JavaScript that supports many different use cases.
https://npmjs.org/package/traverse
https://github.com/substack/js-traverse
It works with all kinds of JavaScript objects. It even detects cycles.
It provides the path of each node, too.
I've created library to traverse and edit deep nested JS objects. Check out API here: https://github.com/dominik791
You can also play with the library interactively using demo app: https://dominik791.github.io/obj-traverse-demo/
Examples of usage: You should always have root object which is the first parameter of each method:
var rootObj = {
name: 'rootObject',
children: [
{
'name': 'child1',
children: [ ... ]
},
{
'name': 'child2',
children: [ ... ]
}
]
};
The second parameter is always the name of property that holds nested objects. In above case it would be 'children'
.
The third parameter is an object that you use to find object/objects that you want to find/modify/delete. For example if you're looking for object with id equal to 1, then you will pass { id: 1}
as the third parameter.
And you can:
findFirst(rootObj, 'children', { id: 1 })
to find first object
with id === 1
findAll(rootObj, 'children', { id: 1 })
to find all objects
with id === 1
findAndDeleteFirst(rootObj, 'children', { id: 1 })
to delete first matching objectfindAndDeleteAll(rootObj, 'children', { id: 1 })
to delete all matching objectsreplacementObj
is used as the last parameter in two last methods:
findAndModifyFirst(rootObj, 'children', { id: 1 }, { id: 2, name: 'newObj'})
to change first found object with id === 1
to the { id: 2, name: 'newObj'}
findAndModifyAll(rootObj, 'children', { id: 1 }, { id: 2, name: 'newObj'})
to change all objects with id === 1
to the { id: 2, name: 'newObj'}
The best solution for me was the following:
simple and without using any framework
var doSomethingForAll = function (arg) {
if (arg != undefined && arg.length > 0) {
arg.map(function (item) {
// do something for item
doSomethingForAll (item.subitem)
});
}
}
var localdata = [{''}]// Your json array
for (var j = 0; j < localdata.length; j++)
{$(localdata).each(function(index,item)
{
$('#tbl').append('<tr><td>' + item.FirstName +'</td></tr>);
}
If you think jQuery is kind of overkill for such a primitive task, you could do something like that:
//your object
var o = {
foo:"bar",
arr:[1,2,3],
subo: {
foo2:"bar2"
}
};
//called with every property and its value
function process(key,value) {
console.log(key + " : "+value);
}
function traverse(o,func) {
for (var i in o) {
func.apply(this,[i,o[i]]);
if (o[i] !== null && typeof(o[i])=="object") {
//going one step down in the object tree!!
traverse(o[i],func);
}
}
}
//that's all... no magic, no bloated framework
traverse(o,process);
You can get all keys / values and preserve the hierarchy with this
// get keys of an object or array
function getkeys(z){
var out=[];
for(var i in z){out.push(i)};
return out;
}
// print all inside an object
function allInternalObjs(data, name) {
name = name || 'data';
return getkeys(data).reduce(function(olist, k){
var v = data[k];
if(typeof v === 'object') { olist.push.apply(olist, allInternalObjs(v, name + '.' + k)); }
else { olist.push(name + '.' + k + ' = ' + v); }
return olist;
}, []);
}
// run with this
allInternalObjs({'a':[{'b':'c'},{'d':{'e':5}}],'f':{'g':'h'}}, 'ob')
This is a modification on (https://stackoverflow.com/a/25063574/1484447)