Traverse all the Nodes of a JSON Object Tree with JavaScript
up vote
127
down vote
favorite
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 so many tutorials showing how to traverse an XML tree with DOM :(
javascript json
add a comment |
up vote
127
down vote
favorite
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 so many tutorials showing how to traverse an XML tree with DOM :(
javascript json
add a comment |
up vote
127
down vote
favorite
up vote
127
down vote
favorite
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 so many tutorials showing how to traverse an XML tree with DOM :(
javascript json
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 so many tutorials showing how to traverse an XML tree with DOM :(
javascript json
javascript json
edited Aug 18 '15 at 12:56
Patsy Issa
9,17433965
9,17433965
asked Apr 6 '09 at 18:45
Takis Chan
add a comment |
add a comment |
15 Answers
15
active
oldest
votes
up vote
197
down vote
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);
2
Why fund.apply(this,...)? Shouldn't it be func.apply(o,...) ?
– Craig Celeste
Jan 23 '14 at 1:39
3
@ParchedSquid No. If you look at the API docs for apply() the first parameter is thethis
value in the target function, whereaso
should be the first parameter to the function. Setting it tothis
(which would be thetraverse
function) is a bit odd though, but it's not likeprocess
uses thethis
reference anyway. It could just as well have been null.
– Thor84no
May 13 '15 at 14:14
1
For jshint in strict mode though you may need to add/*jshint validthis: true */
abovefunc.apply(this,[i,o[i]]);
to avoid the errorW040: Possible strict violation.
caused by the use ofthis
– Jasdeep Khalsa
Jul 3 '15 at 13:37
4
@jasdeepkhalsa: That true. But at the time of the writing of the answer jshint wasn't even started as a project for one and a half year.
– TheHippo
Jul 3 '15 at 17:14
1
@Vishal you could add a 3 parameter to thetraverse
function which tracks the depth. Wenn calling recursively add 1 to the current level.
– TheHippo
Jul 15 '16 at 12:21
|
show 11 more comments
up vote
55
down vote
A JSON object is simply a Javascript object. That's actually what JSON stands for: JavaScript Object Notation. So you'd traverse a JSON object however you'd choose to "traverse" a Javascript object in general.
In ES2017 you would do:
Object.entries(jsonObj).forEach(([key, value]) => {
// do something with key and val
});
You can always write a function to recursively descend into the object:
function traverse(jsonObj) {
if( jsonObj !== null && typeof jsonObj == "object" ) {
Object.entries(jsonObj).forEach(([key, value]) => {
// key is either an array index or object key
traverse(value);
});
}
else {
// jsonObj is a number or string
}
}
This should be a good starting point. I highly recommend using modern javascript methods for such things, since they make writing such code much easier.
7
Avoid traverse(v) where v==null, because (typeof null == "object") === true.function traverse(jsonObj) { if(jsonObj && typeof jsonObj == "object" ) { ...
– Marcelo Amorim
May 26 '17 at 20:16
add a comment |
up vote
29
down vote
function traverse(o ) {
for (i in o) {
if (!!o[i] && typeof(o[i])=="object") {
console.log(i, o[i])
traverse(o[i] );
}
}
}
5
Could you explain why it ismuch better
?
– Dementic
Jul 28 '14 at 7:53
3
If the method is meant to do anything other than log you should check for null, null is still an object.
– wi1
Aug 29 '14 at 4:52
3
@wi1 Agree with you, could check for!!o[i] && typeof o[i] == 'object'
– pilau
Feb 2 '15 at 12:09
add a comment |
up vote
27
down vote
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.
1
js-traverse seems to also be available via npm in node.js.
– Ville
Dec 27 '12 at 21:20
Yes. It's just called traverse there. And they have a lovely web page! Updating my answer to include it.
– Ben Atkin
Dec 27 '12 at 23:31
Thanks for pointing to js-traverse. However, strictly speaking, a link does not replace a proper answer, i.e. one with a code sample.
– Christophe Strobbe
Jul 6 '17 at 21:45
add a comment |
up vote
12
down vote
Depends on what you want to do. Here's an example of traversing a JavaScript object tree, printing keys and values as it goes:
function js_traverse(o) {
var type = typeof o
if (type == "object") {
for (var key in o) {
print("key: ", key)
js_traverse(o[key])
}
} else {
print(o)
}
}
js> foobar = {foo: "bar", baz: "quux", zot: [1, 2, 3, {some: "hash"}]}
[object Object]
js> js_traverse(foobar)
key: foo
bar
key: baz
quux
key: zot
key: 0
1
key: 1
2
key: 2
3
key: 3
key: some
hash
add a comment |
up vote
7
down vote
If you're traversing an actual JSON string then you can use a reviver function.
function traverse (json, callback) {
JSON.parse(json, function (key, value) {
if (key !== '') {
callback.call(this, key, value)
}
return value
})
}
traverse('{"a":{"b":{"c":{"d":1}},"e":{"f":2}}}', function (key, value) {
console.log(arguments)
})
When traversing an object:
function traverse (obj, callback, trail) {
trail = trail ||
Object.keys(obj).forEach(function (key) {
var value = obj[key]
if (Object.getPrototypeOf(value) === Object.prototype) {
traverse(value, callback, trail.concat(key))
} else {
callback.call(obj, key, value, trail)
}
})
}
traverse({a: {b: {c: {d: 1}}, e: {f: 2}}}, function (key, value, trail) {
console.log(arguments)
})
add a comment |
up vote
4
down vote
I wanted to use the perfect solution of @TheHippo in an anonymous function, without use of process and trigger functions. The following worked for me, sharing for novice programmers like myself.
(function traverse(o) {
for (var i in o) {
console.log('key : ' + i + ', value: ' + o[i]);
if (o[i] !== null && typeof(o[i])=="object") {
//going on step down in the object tree!!
traverse(o[i]);
}
}
})
(json);
Thanks for this!
– Mike
Nov 4 '16 at 3:01
add a comment |
up vote
2
down vote
Most Javascript engines do not optimize tail recursion (this might not be an issue if your JSON isn't deeply nested), but I usually err on the side of caution and do iteration instead, e.g.
function traverse(o, fn) {
const stack = [o]
while (stack.length) {
const obj = stack.shift()
Object.keys(obj).forEach((key) => {
fn(key, obj[key], obj)
if (obj[key] instanceof Object) {
stack.unshift(obj[key])
return
}
})
}
}
const o = {
name: 'Max',
legal: false,
other: {
name: 'Maxwell',
nested: {
legal: true
}
}
}
const fx = (key, value, obj) => console.log(key, value)
traverse(o, fx)
add a comment |
up vote
1
down vote
For a newer way to do it if you don't mind dropping IE and mainly supporting more current browsers (check kangax's es6 table for compatibility). You can use es2015 generators for this. I've updated @TheHippo's answer accordingly. Of course if you really want IE support you can use the babel JavaScript transpiler.
//your object
var o = {
foo:"bar",
arr:[1,2,3],
subo: {
foo2:"bar2"
}
};
function* traverse(o,func) {
for (var i in o) {
yield [i,o[i]];
if (o[i] !== null && typeof(o[i])=="object") {
//going one step down in the object tree!!
yield* traverse(o[i],func);
}
}
}
//that's all... no magic, no bloated framework
for(var [key, value] of traverse(o)) {
console.log(key, value);
}
If you want only own enumerable properties (basically non-prototype chain properties) you can change it to iterate using Object.keys
and a for...of
loop instead:
//your object
var o = {
foo:"bar",
arr:[1,2,3],
subo: {
foo2:"bar2"
}
};
function* traverse(o,func) {
for (var i of Object.keys(o)) {
yield [i,o[i]];
if (o[i] !== null && typeof(o[i])=="object") {
//going one step down in the object tree!!
yield* traverse(o[i],func);
}
}
}
//that's all... no magic, no bloated framework
for(var [key, value] of traverse(o)) {
console.log(key, value);
}
add a comment |
up vote
0
down vote
My Script:
op_needed = ;
callback_func = function(val) {
var i, j, len;
results = ;
for (j = 0, len = val.length; j < len; j++) {
i = val[j];
if (i['children'].length !== 0) {
call_func(i['children']);
} else {
op_needed.push(i['rel_path']);
}
}
return op_needed;
};
Input JSON:
[
{
"id": null,
"name": "output",
"asset_type_assoc": ,
"rel_path": "output",
"children": [
{
"id": null,
"name": "output",
"asset_type_assoc": ,
"rel_path": "output/f1",
"children": [
{
"id": null,
"name": "v#",
"asset_type_assoc": ,
"rel_path": "output/f1/ver",
"children":
}
]
}
]
}
]
Function Call:
callback_func(inp_json);
Output as per my Need:
["output/f1/ver"]
add a comment |
up vote
0
down vote
var test = {
depth00: {
depth10: 'string'
, depth11: 11
, depth12: {
depth20:'string'
, depth21:21
}
, depth13: [
{
depth22:'2201'
, depth23:'2301'
}
, {
depth22:'2202'
, depth23:'2302'
}
]
}
,depth01: {
depth10: 'string'
, depth11: 11
, depth12: {
depth20:'string'
, depth21:21
}
, depth13: [
{
depth22:'2201'
, depth23:'2301'
}
, {
depth22:'2202'
, depth23:'2302'
}
]
}
, depth02: 'string'
, dpeth03: 3
};
function traverse(result, obj, preKey) {
if(!obj) return ;
if (typeof obj == 'object') {
for(var key in obj) {
traverse(result, obj[key], (preKey || '') + (preKey ? '[' + key + ']' : key))
}
} else {
result.push({
key: (preKey || '')
, val: obj
});
}
return result;
}
document.getElementById('textarea').value = JSON.stringify(traverse(, test), null, 2);
<textarea style="width:100%;height:600px;" id="textarea"></textarea>
made it to submit form enctype applicatioin/json
– seung
Nov 24 '17 at 12:39
add a comment |
up vote
-1
down vote
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)
});
}
}
why downvoted? can someone explain it?
– Asqan
Sep 29 '15 at 10:01
add a comment |
up vote
-1
down vote
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)
add a comment |
up vote
-1
down vote
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>);
}
add a comment |
up vote
-1
down vote
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
withid === 1
findAll(rootObj, 'children', { id: 1 })
to find all objects
withid === 1
findAndDeleteFirst(rootObj, 'children', { id: 1 })
to delete first matching object
findAndDeleteAll(rootObj, 'children', { id: 1 })
to delete all matching objects
replacementObj
is used as the last parameter in two last methods:
findAndModifyFirst(rootObj, 'children', { id: 1 }, { id: 2, name: 'newObj'})
to change first found object withid === 1
to the{ id: 2, name: 'newObj'}
findAndModifyAll(rootObj, 'children', { id: 1 }, { id: 2, name: 'newObj'})
to change all objects withid === 1
to the{ id: 2, name: 'newObj'}
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f722668%2ftraverse-all-the-nodes-of-a-json-object-tree-with-javascript%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
15 Answers
15
active
oldest
votes
15 Answers
15
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
197
down vote
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);
2
Why fund.apply(this,...)? Shouldn't it be func.apply(o,...) ?
– Craig Celeste
Jan 23 '14 at 1:39
3
@ParchedSquid No. If you look at the API docs for apply() the first parameter is thethis
value in the target function, whereaso
should be the first parameter to the function. Setting it tothis
(which would be thetraverse
function) is a bit odd though, but it's not likeprocess
uses thethis
reference anyway. It could just as well have been null.
– Thor84no
May 13 '15 at 14:14
1
For jshint in strict mode though you may need to add/*jshint validthis: true */
abovefunc.apply(this,[i,o[i]]);
to avoid the errorW040: Possible strict violation.
caused by the use ofthis
– Jasdeep Khalsa
Jul 3 '15 at 13:37
4
@jasdeepkhalsa: That true. But at the time of the writing of the answer jshint wasn't even started as a project for one and a half year.
– TheHippo
Jul 3 '15 at 17:14
1
@Vishal you could add a 3 parameter to thetraverse
function which tracks the depth. Wenn calling recursively add 1 to the current level.
– TheHippo
Jul 15 '16 at 12:21
|
show 11 more comments
up vote
197
down vote
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);
2
Why fund.apply(this,...)? Shouldn't it be func.apply(o,...) ?
– Craig Celeste
Jan 23 '14 at 1:39
3
@ParchedSquid No. If you look at the API docs for apply() the first parameter is thethis
value in the target function, whereaso
should be the first parameter to the function. Setting it tothis
(which would be thetraverse
function) is a bit odd though, but it's not likeprocess
uses thethis
reference anyway. It could just as well have been null.
– Thor84no
May 13 '15 at 14:14
1
For jshint in strict mode though you may need to add/*jshint validthis: true */
abovefunc.apply(this,[i,o[i]]);
to avoid the errorW040: Possible strict violation.
caused by the use ofthis
– Jasdeep Khalsa
Jul 3 '15 at 13:37
4
@jasdeepkhalsa: That true. But at the time of the writing of the answer jshint wasn't even started as a project for one and a half year.
– TheHippo
Jul 3 '15 at 17:14
1
@Vishal you could add a 3 parameter to thetraverse
function which tracks the depth. Wenn calling recursively add 1 to the current level.
– TheHippo
Jul 15 '16 at 12:21
|
show 11 more comments
up vote
197
down vote
up vote
197
down vote
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);
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);
edited Mar 16 '17 at 16:27
lleaff
2,707518
2,707518
answered Apr 6 '09 at 19:05
TheHippo
42.4k116392
42.4k116392
2
Why fund.apply(this,...)? Shouldn't it be func.apply(o,...) ?
– Craig Celeste
Jan 23 '14 at 1:39
3
@ParchedSquid No. If you look at the API docs for apply() the first parameter is thethis
value in the target function, whereaso
should be the first parameter to the function. Setting it tothis
(which would be thetraverse
function) is a bit odd though, but it's not likeprocess
uses thethis
reference anyway. It could just as well have been null.
– Thor84no
May 13 '15 at 14:14
1
For jshint in strict mode though you may need to add/*jshint validthis: true */
abovefunc.apply(this,[i,o[i]]);
to avoid the errorW040: Possible strict violation.
caused by the use ofthis
– Jasdeep Khalsa
Jul 3 '15 at 13:37
4
@jasdeepkhalsa: That true. But at the time of the writing of the answer jshint wasn't even started as a project for one and a half year.
– TheHippo
Jul 3 '15 at 17:14
1
@Vishal you could add a 3 parameter to thetraverse
function which tracks the depth. Wenn calling recursively add 1 to the current level.
– TheHippo
Jul 15 '16 at 12:21
|
show 11 more comments
2
Why fund.apply(this,...)? Shouldn't it be func.apply(o,...) ?
– Craig Celeste
Jan 23 '14 at 1:39
3
@ParchedSquid No. If you look at the API docs for apply() the first parameter is thethis
value in the target function, whereaso
should be the first parameter to the function. Setting it tothis
(which would be thetraverse
function) is a bit odd though, but it's not likeprocess
uses thethis
reference anyway. It could just as well have been null.
– Thor84no
May 13 '15 at 14:14
1
For jshint in strict mode though you may need to add/*jshint validthis: true */
abovefunc.apply(this,[i,o[i]]);
to avoid the errorW040: Possible strict violation.
caused by the use ofthis
– Jasdeep Khalsa
Jul 3 '15 at 13:37
4
@jasdeepkhalsa: That true. But at the time of the writing of the answer jshint wasn't even started as a project for one and a half year.
– TheHippo
Jul 3 '15 at 17:14
1
@Vishal you could add a 3 parameter to thetraverse
function which tracks the depth. Wenn calling recursively add 1 to the current level.
– TheHippo
Jul 15 '16 at 12:21
2
2
Why fund.apply(this,...)? Shouldn't it be func.apply(o,...) ?
– Craig Celeste
Jan 23 '14 at 1:39
Why fund.apply(this,...)? Shouldn't it be func.apply(o,...) ?
– Craig Celeste
Jan 23 '14 at 1:39
3
3
@ParchedSquid No. If you look at the API docs for apply() the first parameter is the
this
value in the target function, whereas o
should be the first parameter to the function. Setting it to this
(which would be the traverse
function) is a bit odd though, but it's not like process
uses the this
reference anyway. It could just as well have been null.– Thor84no
May 13 '15 at 14:14
@ParchedSquid No. If you look at the API docs for apply() the first parameter is the
this
value in the target function, whereas o
should be the first parameter to the function. Setting it to this
(which would be the traverse
function) is a bit odd though, but it's not like process
uses the this
reference anyway. It could just as well have been null.– Thor84no
May 13 '15 at 14:14
1
1
For jshint in strict mode though you may need to add
/*jshint validthis: true */
above func.apply(this,[i,o[i]]);
to avoid the error W040: Possible strict violation.
caused by the use of this
– Jasdeep Khalsa
Jul 3 '15 at 13:37
For jshint in strict mode though you may need to add
/*jshint validthis: true */
above func.apply(this,[i,o[i]]);
to avoid the error W040: Possible strict violation.
caused by the use of this
– Jasdeep Khalsa
Jul 3 '15 at 13:37
4
4
@jasdeepkhalsa: That true. But at the time of the writing of the answer jshint wasn't even started as a project for one and a half year.
– TheHippo
Jul 3 '15 at 17:14
@jasdeepkhalsa: That true. But at the time of the writing of the answer jshint wasn't even started as a project for one and a half year.
– TheHippo
Jul 3 '15 at 17:14
1
1
@Vishal you could add a 3 parameter to the
traverse
function which tracks the depth. Wenn calling recursively add 1 to the current level.– TheHippo
Jul 15 '16 at 12:21
@Vishal you could add a 3 parameter to the
traverse
function which tracks the depth. Wenn calling recursively add 1 to the current level.– TheHippo
Jul 15 '16 at 12:21
|
show 11 more comments
up vote
55
down vote
A JSON object is simply a Javascript object. That's actually what JSON stands for: JavaScript Object Notation. So you'd traverse a JSON object however you'd choose to "traverse" a Javascript object in general.
In ES2017 you would do:
Object.entries(jsonObj).forEach(([key, value]) => {
// do something with key and val
});
You can always write a function to recursively descend into the object:
function traverse(jsonObj) {
if( jsonObj !== null && typeof jsonObj == "object" ) {
Object.entries(jsonObj).forEach(([key, value]) => {
// key is either an array index or object key
traverse(value);
});
}
else {
// jsonObj is a number or string
}
}
This should be a good starting point. I highly recommend using modern javascript methods for such things, since they make writing such code much easier.
7
Avoid traverse(v) where v==null, because (typeof null == "object") === true.function traverse(jsonObj) { if(jsonObj && typeof jsonObj == "object" ) { ...
– Marcelo Amorim
May 26 '17 at 20:16
add a comment |
up vote
55
down vote
A JSON object is simply a Javascript object. That's actually what JSON stands for: JavaScript Object Notation. So you'd traverse a JSON object however you'd choose to "traverse" a Javascript object in general.
In ES2017 you would do:
Object.entries(jsonObj).forEach(([key, value]) => {
// do something with key and val
});
You can always write a function to recursively descend into the object:
function traverse(jsonObj) {
if( jsonObj !== null && typeof jsonObj == "object" ) {
Object.entries(jsonObj).forEach(([key, value]) => {
// key is either an array index or object key
traverse(value);
});
}
else {
// jsonObj is a number or string
}
}
This should be a good starting point. I highly recommend using modern javascript methods for such things, since they make writing such code much easier.
7
Avoid traverse(v) where v==null, because (typeof null == "object") === true.function traverse(jsonObj) { if(jsonObj && typeof jsonObj == "object" ) { ...
– Marcelo Amorim
May 26 '17 at 20:16
add a comment |
up vote
55
down vote
up vote
55
down vote
A JSON object is simply a Javascript object. That's actually what JSON stands for: JavaScript Object Notation. So you'd traverse a JSON object however you'd choose to "traverse" a Javascript object in general.
In ES2017 you would do:
Object.entries(jsonObj).forEach(([key, value]) => {
// do something with key and val
});
You can always write a function to recursively descend into the object:
function traverse(jsonObj) {
if( jsonObj !== null && typeof jsonObj == "object" ) {
Object.entries(jsonObj).forEach(([key, value]) => {
// key is either an array index or object key
traverse(value);
});
}
else {
// jsonObj is a number or string
}
}
This should be a good starting point. I highly recommend using modern javascript methods for such things, since they make writing such code much easier.
A JSON object is simply a Javascript object. That's actually what JSON stands for: JavaScript Object Notation. So you'd traverse a JSON object however you'd choose to "traverse" a Javascript object in general.
In ES2017 you would do:
Object.entries(jsonObj).forEach(([key, value]) => {
// do something with key and val
});
You can always write a function to recursively descend into the object:
function traverse(jsonObj) {
if( jsonObj !== null && typeof jsonObj == "object" ) {
Object.entries(jsonObj).forEach(([key, value]) => {
// key is either an array index or object key
traverse(value);
});
}
else {
// jsonObj is a number or string
}
}
This should be a good starting point. I highly recommend using modern javascript methods for such things, since they make writing such code much easier.
edited Nov 19 at 23:49
Devin G Rhode
14.2k52543
14.2k52543
answered Apr 6 '09 at 18:47
Eli Courtwright
118k55194246
118k55194246
7
Avoid traverse(v) where v==null, because (typeof null == "object") === true.function traverse(jsonObj) { if(jsonObj && typeof jsonObj == "object" ) { ...
– Marcelo Amorim
May 26 '17 at 20:16
add a comment |
7
Avoid traverse(v) where v==null, because (typeof null == "object") === true.function traverse(jsonObj) { if(jsonObj && typeof jsonObj == "object" ) { ...
– Marcelo Amorim
May 26 '17 at 20:16
7
7
Avoid traverse(v) where v==null, because (typeof null == "object") === true.
function traverse(jsonObj) { if(jsonObj && typeof jsonObj == "object" ) { ...
– Marcelo Amorim
May 26 '17 at 20:16
Avoid traverse(v) where v==null, because (typeof null == "object") === true.
function traverse(jsonObj) { if(jsonObj && typeof jsonObj == "object" ) { ...
– Marcelo Amorim
May 26 '17 at 20:16
add a comment |
up vote
29
down vote
function traverse(o ) {
for (i in o) {
if (!!o[i] && typeof(o[i])=="object") {
console.log(i, o[i])
traverse(o[i] );
}
}
}
5
Could you explain why it ismuch better
?
– Dementic
Jul 28 '14 at 7:53
3
If the method is meant to do anything other than log you should check for null, null is still an object.
– wi1
Aug 29 '14 at 4:52
3
@wi1 Agree with you, could check for!!o[i] && typeof o[i] == 'object'
– pilau
Feb 2 '15 at 12:09
add a comment |
up vote
29
down vote
function traverse(o ) {
for (i in o) {
if (!!o[i] && typeof(o[i])=="object") {
console.log(i, o[i])
traverse(o[i] );
}
}
}
5
Could you explain why it ismuch better
?
– Dementic
Jul 28 '14 at 7:53
3
If the method is meant to do anything other than log you should check for null, null is still an object.
– wi1
Aug 29 '14 at 4:52
3
@wi1 Agree with you, could check for!!o[i] && typeof o[i] == 'object'
– pilau
Feb 2 '15 at 12:09
add a comment |
up vote
29
down vote
up vote
29
down vote
function traverse(o ) {
for (i in o) {
if (!!o[i] && typeof(o[i])=="object") {
console.log(i, o[i])
traverse(o[i] );
}
}
}
function traverse(o ) {
for (i in o) {
if (!!o[i] && typeof(o[i])=="object") {
console.log(i, o[i])
traverse(o[i] );
}
}
}
edited Jan 24 at 17:02
George Jempty
6,9501161130
6,9501161130
answered Jan 24 '12 at 12:34
tejas
30732
30732
5
Could you explain why it ismuch better
?
– Dementic
Jul 28 '14 at 7:53
3
If the method is meant to do anything other than log you should check for null, null is still an object.
– wi1
Aug 29 '14 at 4:52
3
@wi1 Agree with you, could check for!!o[i] && typeof o[i] == 'object'
– pilau
Feb 2 '15 at 12:09
add a comment |
5
Could you explain why it ismuch better
?
– Dementic
Jul 28 '14 at 7:53
3
If the method is meant to do anything other than log you should check for null, null is still an object.
– wi1
Aug 29 '14 at 4:52
3
@wi1 Agree with you, could check for!!o[i] && typeof o[i] == 'object'
– pilau
Feb 2 '15 at 12:09
5
5
Could you explain why it is
much better
?– Dementic
Jul 28 '14 at 7:53
Could you explain why it is
much better
?– Dementic
Jul 28 '14 at 7:53
3
3
If the method is meant to do anything other than log you should check for null, null is still an object.
– wi1
Aug 29 '14 at 4:52
If the method is meant to do anything other than log you should check for null, null is still an object.
– wi1
Aug 29 '14 at 4:52
3
3
@wi1 Agree with you, could check for
!!o[i] && typeof o[i] == 'object'
– pilau
Feb 2 '15 at 12:09
@wi1 Agree with you, could check for
!!o[i] && typeof o[i] == 'object'
– pilau
Feb 2 '15 at 12:09
add a comment |
up vote
27
down vote
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.
1
js-traverse seems to also be available via npm in node.js.
– Ville
Dec 27 '12 at 21:20
Yes. It's just called traverse there. And they have a lovely web page! Updating my answer to include it.
– Ben Atkin
Dec 27 '12 at 23:31
Thanks for pointing to js-traverse. However, strictly speaking, a link does not replace a proper answer, i.e. one with a code sample.
– Christophe Strobbe
Jul 6 '17 at 21:45
add a comment |
up vote
27
down vote
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.
1
js-traverse seems to also be available via npm in node.js.
– Ville
Dec 27 '12 at 21:20
Yes. It's just called traverse there. And they have a lovely web page! Updating my answer to include it.
– Ben Atkin
Dec 27 '12 at 23:31
Thanks for pointing to js-traverse. However, strictly speaking, a link does not replace a proper answer, i.e. one with a code sample.
– Christophe Strobbe
Jul 6 '17 at 21:45
add a comment |
up vote
27
down vote
up vote
27
down vote
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.
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.
edited Dec 27 '12 at 23:31
answered Jun 17 '11 at 20:41
Ben Atkin
10.3k54250
10.3k54250
1
js-traverse seems to also be available via npm in node.js.
– Ville
Dec 27 '12 at 21:20
Yes. It's just called traverse there. And they have a lovely web page! Updating my answer to include it.
– Ben Atkin
Dec 27 '12 at 23:31
Thanks for pointing to js-traverse. However, strictly speaking, a link does not replace a proper answer, i.e. one with a code sample.
– Christophe Strobbe
Jul 6 '17 at 21:45
add a comment |
1
js-traverse seems to also be available via npm in node.js.
– Ville
Dec 27 '12 at 21:20
Yes. It's just called traverse there. And they have a lovely web page! Updating my answer to include it.
– Ben Atkin
Dec 27 '12 at 23:31
Thanks for pointing to js-traverse. However, strictly speaking, a link does not replace a proper answer, i.e. one with a code sample.
– Christophe Strobbe
Jul 6 '17 at 21:45
1
1
js-traverse seems to also be available via npm in node.js.
– Ville
Dec 27 '12 at 21:20
js-traverse seems to also be available via npm in node.js.
– Ville
Dec 27 '12 at 21:20
Yes. It's just called traverse there. And they have a lovely web page! Updating my answer to include it.
– Ben Atkin
Dec 27 '12 at 23:31
Yes. It's just called traverse there. And they have a lovely web page! Updating my answer to include it.
– Ben Atkin
Dec 27 '12 at 23:31
Thanks for pointing to js-traverse. However, strictly speaking, a link does not replace a proper answer, i.e. one with a code sample.
– Christophe Strobbe
Jul 6 '17 at 21:45
Thanks for pointing to js-traverse. However, strictly speaking, a link does not replace a proper answer, i.e. one with a code sample.
– Christophe Strobbe
Jul 6 '17 at 21:45
add a comment |
up vote
12
down vote
Depends on what you want to do. Here's an example of traversing a JavaScript object tree, printing keys and values as it goes:
function js_traverse(o) {
var type = typeof o
if (type == "object") {
for (var key in o) {
print("key: ", key)
js_traverse(o[key])
}
} else {
print(o)
}
}
js> foobar = {foo: "bar", baz: "quux", zot: [1, 2, 3, {some: "hash"}]}
[object Object]
js> js_traverse(foobar)
key: foo
bar
key: baz
quux
key: zot
key: 0
1
key: 1
2
key: 2
3
key: 3
key: some
hash
add a comment |
up vote
12
down vote
Depends on what you want to do. Here's an example of traversing a JavaScript object tree, printing keys and values as it goes:
function js_traverse(o) {
var type = typeof o
if (type == "object") {
for (var key in o) {
print("key: ", key)
js_traverse(o[key])
}
} else {
print(o)
}
}
js> foobar = {foo: "bar", baz: "quux", zot: [1, 2, 3, {some: "hash"}]}
[object Object]
js> js_traverse(foobar)
key: foo
bar
key: baz
quux
key: zot
key: 0
1
key: 1
2
key: 2
3
key: 3
key: some
hash
add a comment |
up vote
12
down vote
up vote
12
down vote
Depends on what you want to do. Here's an example of traversing a JavaScript object tree, printing keys and values as it goes:
function js_traverse(o) {
var type = typeof o
if (type == "object") {
for (var key in o) {
print("key: ", key)
js_traverse(o[key])
}
} else {
print(o)
}
}
js> foobar = {foo: "bar", baz: "quux", zot: [1, 2, 3, {some: "hash"}]}
[object Object]
js> js_traverse(foobar)
key: foo
bar
key: baz
quux
key: zot
key: 0
1
key: 1
2
key: 2
3
key: 3
key: some
hash
Depends on what you want to do. Here's an example of traversing a JavaScript object tree, printing keys and values as it goes:
function js_traverse(o) {
var type = typeof o
if (type == "object") {
for (var key in o) {
print("key: ", key)
js_traverse(o[key])
}
} else {
print(o)
}
}
js> foobar = {foo: "bar", baz: "quux", zot: [1, 2, 3, {some: "hash"}]}
[object Object]
js> js_traverse(foobar)
key: foo
bar
key: baz
quux
key: zot
key: 0
1
key: 1
2
key: 2
3
key: 3
key: some
hash
answered Apr 6 '09 at 19:06
Brian Campbell
229k48311318
229k48311318
add a comment |
add a comment |
up vote
7
down vote
If you're traversing an actual JSON string then you can use a reviver function.
function traverse (json, callback) {
JSON.parse(json, function (key, value) {
if (key !== '') {
callback.call(this, key, value)
}
return value
})
}
traverse('{"a":{"b":{"c":{"d":1}},"e":{"f":2}}}', function (key, value) {
console.log(arguments)
})
When traversing an object:
function traverse (obj, callback, trail) {
trail = trail ||
Object.keys(obj).forEach(function (key) {
var value = obj[key]
if (Object.getPrototypeOf(value) === Object.prototype) {
traverse(value, callback, trail.concat(key))
} else {
callback.call(obj, key, value, trail)
}
})
}
traverse({a: {b: {c: {d: 1}}, e: {f: 2}}}, function (key, value, trail) {
console.log(arguments)
})
add a comment |
up vote
7
down vote
If you're traversing an actual JSON string then you can use a reviver function.
function traverse (json, callback) {
JSON.parse(json, function (key, value) {
if (key !== '') {
callback.call(this, key, value)
}
return value
})
}
traverse('{"a":{"b":{"c":{"d":1}},"e":{"f":2}}}', function (key, value) {
console.log(arguments)
})
When traversing an object:
function traverse (obj, callback, trail) {
trail = trail ||
Object.keys(obj).forEach(function (key) {
var value = obj[key]
if (Object.getPrototypeOf(value) === Object.prototype) {
traverse(value, callback, trail.concat(key))
} else {
callback.call(obj, key, value, trail)
}
})
}
traverse({a: {b: {c: {d: 1}}, e: {f: 2}}}, function (key, value, trail) {
console.log(arguments)
})
add a comment |
up vote
7
down vote
up vote
7
down vote
If you're traversing an actual JSON string then you can use a reviver function.
function traverse (json, callback) {
JSON.parse(json, function (key, value) {
if (key !== '') {
callback.call(this, key, value)
}
return value
})
}
traverse('{"a":{"b":{"c":{"d":1}},"e":{"f":2}}}', function (key, value) {
console.log(arguments)
})
When traversing an object:
function traverse (obj, callback, trail) {
trail = trail ||
Object.keys(obj).forEach(function (key) {
var value = obj[key]
if (Object.getPrototypeOf(value) === Object.prototype) {
traverse(value, callback, trail.concat(key))
} else {
callback.call(obj, key, value, trail)
}
})
}
traverse({a: {b: {c: {d: 1}}, e: {f: 2}}}, function (key, value, trail) {
console.log(arguments)
})
If you're traversing an actual JSON string then you can use a reviver function.
function traverse (json, callback) {
JSON.parse(json, function (key, value) {
if (key !== '') {
callback.call(this, key, value)
}
return value
})
}
traverse('{"a":{"b":{"c":{"d":1}},"e":{"f":2}}}', function (key, value) {
console.log(arguments)
})
When traversing an object:
function traverse (obj, callback, trail) {
trail = trail ||
Object.keys(obj).forEach(function (key) {
var value = obj[key]
if (Object.getPrototypeOf(value) === Object.prototype) {
traverse(value, callback, trail.concat(key))
} else {
callback.call(obj, key, value, trail)
}
})
}
traverse({a: {b: {c: {d: 1}}, e: {f: 2}}}, function (key, value, trail) {
console.log(arguments)
})
edited Oct 8 '15 at 17:25
answered Oct 8 '15 at 17:17
David Lane
98664
98664
add a comment |
add a comment |
up vote
4
down vote
I wanted to use the perfect solution of @TheHippo in an anonymous function, without use of process and trigger functions. The following worked for me, sharing for novice programmers like myself.
(function traverse(o) {
for (var i in o) {
console.log('key : ' + i + ', value: ' + o[i]);
if (o[i] !== null && typeof(o[i])=="object") {
//going on step down in the object tree!!
traverse(o[i]);
}
}
})
(json);
Thanks for this!
– Mike
Nov 4 '16 at 3:01
add a comment |
up vote
4
down vote
I wanted to use the perfect solution of @TheHippo in an anonymous function, without use of process and trigger functions. The following worked for me, sharing for novice programmers like myself.
(function traverse(o) {
for (var i in o) {
console.log('key : ' + i + ', value: ' + o[i]);
if (o[i] !== null && typeof(o[i])=="object") {
//going on step down in the object tree!!
traverse(o[i]);
}
}
})
(json);
Thanks for this!
– Mike
Nov 4 '16 at 3:01
add a comment |
up vote
4
down vote
up vote
4
down vote
I wanted to use the perfect solution of @TheHippo in an anonymous function, without use of process and trigger functions. The following worked for me, sharing for novice programmers like myself.
(function traverse(o) {
for (var i in o) {
console.log('key : ' + i + ', value: ' + o[i]);
if (o[i] !== null && typeof(o[i])=="object") {
//going on step down in the object tree!!
traverse(o[i]);
}
}
})
(json);
I wanted to use the perfect solution of @TheHippo in an anonymous function, without use of process and trigger functions. The following worked for me, sharing for novice programmers like myself.
(function traverse(o) {
for (var i in o) {
console.log('key : ' + i + ', value: ' + o[i]);
if (o[i] !== null && typeof(o[i])=="object") {
//going on step down in the object tree!!
traverse(o[i]);
}
}
})
(json);
answered Aug 11 '15 at 15:28
Raf
4,44611735
4,44611735
Thanks for this!
– Mike
Nov 4 '16 at 3:01
add a comment |
Thanks for this!
– Mike
Nov 4 '16 at 3:01
Thanks for this!
– Mike
Nov 4 '16 at 3:01
Thanks for this!
– Mike
Nov 4 '16 at 3:01
add a comment |
up vote
2
down vote
Most Javascript engines do not optimize tail recursion (this might not be an issue if your JSON isn't deeply nested), but I usually err on the side of caution and do iteration instead, e.g.
function traverse(o, fn) {
const stack = [o]
while (stack.length) {
const obj = stack.shift()
Object.keys(obj).forEach((key) => {
fn(key, obj[key], obj)
if (obj[key] instanceof Object) {
stack.unshift(obj[key])
return
}
})
}
}
const o = {
name: 'Max',
legal: false,
other: {
name: 'Maxwell',
nested: {
legal: true
}
}
}
const fx = (key, value, obj) => console.log(key, value)
traverse(o, fx)
add a comment |
up vote
2
down vote
Most Javascript engines do not optimize tail recursion (this might not be an issue if your JSON isn't deeply nested), but I usually err on the side of caution and do iteration instead, e.g.
function traverse(o, fn) {
const stack = [o]
while (stack.length) {
const obj = stack.shift()
Object.keys(obj).forEach((key) => {
fn(key, obj[key], obj)
if (obj[key] instanceof Object) {
stack.unshift(obj[key])
return
}
})
}
}
const o = {
name: 'Max',
legal: false,
other: {
name: 'Maxwell',
nested: {
legal: true
}
}
}
const fx = (key, value, obj) => console.log(key, value)
traverse(o, fx)
add a comment |
up vote
2
down vote
up vote
2
down vote
Most Javascript engines do not optimize tail recursion (this might not be an issue if your JSON isn't deeply nested), but I usually err on the side of caution and do iteration instead, e.g.
function traverse(o, fn) {
const stack = [o]
while (stack.length) {
const obj = stack.shift()
Object.keys(obj).forEach((key) => {
fn(key, obj[key], obj)
if (obj[key] instanceof Object) {
stack.unshift(obj[key])
return
}
})
}
}
const o = {
name: 'Max',
legal: false,
other: {
name: 'Maxwell',
nested: {
legal: true
}
}
}
const fx = (key, value, obj) => console.log(key, value)
traverse(o, fx)
Most Javascript engines do not optimize tail recursion (this might not be an issue if your JSON isn't deeply nested), but I usually err on the side of caution and do iteration instead, e.g.
function traverse(o, fn) {
const stack = [o]
while (stack.length) {
const obj = stack.shift()
Object.keys(obj).forEach((key) => {
fn(key, obj[key], obj)
if (obj[key] instanceof Object) {
stack.unshift(obj[key])
return
}
})
}
}
const o = {
name: 'Max',
legal: false,
other: {
name: 'Maxwell',
nested: {
legal: true
}
}
}
const fx = (key, value, obj) => console.log(key, value)
traverse(o, fx)
answered Oct 14 '16 at 22:44
Max
61668
61668
add a comment |
add a comment |
up vote
1
down vote
For a newer way to do it if you don't mind dropping IE and mainly supporting more current browsers (check kangax's es6 table for compatibility). You can use es2015 generators for this. I've updated @TheHippo's answer accordingly. Of course if you really want IE support you can use the babel JavaScript transpiler.
//your object
var o = {
foo:"bar",
arr:[1,2,3],
subo: {
foo2:"bar2"
}
};
function* traverse(o,func) {
for (var i in o) {
yield [i,o[i]];
if (o[i] !== null && typeof(o[i])=="object") {
//going one step down in the object tree!!
yield* traverse(o[i],func);
}
}
}
//that's all... no magic, no bloated framework
for(var [key, value] of traverse(o)) {
console.log(key, value);
}
If you want only own enumerable properties (basically non-prototype chain properties) you can change it to iterate using Object.keys
and a for...of
loop instead:
//your object
var o = {
foo:"bar",
arr:[1,2,3],
subo: {
foo2:"bar2"
}
};
function* traverse(o,func) {
for (var i of Object.keys(o)) {
yield [i,o[i]];
if (o[i] !== null && typeof(o[i])=="object") {
//going one step down in the object tree!!
yield* traverse(o[i],func);
}
}
}
//that's all... no magic, no bloated framework
for(var [key, value] of traverse(o)) {
console.log(key, value);
}
add a comment |
up vote
1
down vote
For a newer way to do it if you don't mind dropping IE and mainly supporting more current browsers (check kangax's es6 table for compatibility). You can use es2015 generators for this. I've updated @TheHippo's answer accordingly. Of course if you really want IE support you can use the babel JavaScript transpiler.
//your object
var o = {
foo:"bar",
arr:[1,2,3],
subo: {
foo2:"bar2"
}
};
function* traverse(o,func) {
for (var i in o) {
yield [i,o[i]];
if (o[i] !== null && typeof(o[i])=="object") {
//going one step down in the object tree!!
yield* traverse(o[i],func);
}
}
}
//that's all... no magic, no bloated framework
for(var [key, value] of traverse(o)) {
console.log(key, value);
}
If you want only own enumerable properties (basically non-prototype chain properties) you can change it to iterate using Object.keys
and a for...of
loop instead:
//your object
var o = {
foo:"bar",
arr:[1,2,3],
subo: {
foo2:"bar2"
}
};
function* traverse(o,func) {
for (var i of Object.keys(o)) {
yield [i,o[i]];
if (o[i] !== null && typeof(o[i])=="object") {
//going one step down in the object tree!!
yield* traverse(o[i],func);
}
}
}
//that's all... no magic, no bloated framework
for(var [key, value] of traverse(o)) {
console.log(key, value);
}
add a comment |
up vote
1
down vote
up vote
1
down vote
For a newer way to do it if you don't mind dropping IE and mainly supporting more current browsers (check kangax's es6 table for compatibility). You can use es2015 generators for this. I've updated @TheHippo's answer accordingly. Of course if you really want IE support you can use the babel JavaScript transpiler.
//your object
var o = {
foo:"bar",
arr:[1,2,3],
subo: {
foo2:"bar2"
}
};
function* traverse(o,func) {
for (var i in o) {
yield [i,o[i]];
if (o[i] !== null && typeof(o[i])=="object") {
//going one step down in the object tree!!
yield* traverse(o[i],func);
}
}
}
//that's all... no magic, no bloated framework
for(var [key, value] of traverse(o)) {
console.log(key, value);
}
If you want only own enumerable properties (basically non-prototype chain properties) you can change it to iterate using Object.keys
and a for...of
loop instead:
//your object
var o = {
foo:"bar",
arr:[1,2,3],
subo: {
foo2:"bar2"
}
};
function* traverse(o,func) {
for (var i of Object.keys(o)) {
yield [i,o[i]];
if (o[i] !== null && typeof(o[i])=="object") {
//going one step down in the object tree!!
yield* traverse(o[i],func);
}
}
}
//that's all... no magic, no bloated framework
for(var [key, value] of traverse(o)) {
console.log(key, value);
}
For a newer way to do it if you don't mind dropping IE and mainly supporting more current browsers (check kangax's es6 table for compatibility). You can use es2015 generators for this. I've updated @TheHippo's answer accordingly. Of course if you really want IE support you can use the babel JavaScript transpiler.
//your object
var o = {
foo:"bar",
arr:[1,2,3],
subo: {
foo2:"bar2"
}
};
function* traverse(o,func) {
for (var i in o) {
yield [i,o[i]];
if (o[i] !== null && typeof(o[i])=="object") {
//going one step down in the object tree!!
yield* traverse(o[i],func);
}
}
}
//that's all... no magic, no bloated framework
for(var [key, value] of traverse(o)) {
console.log(key, value);
}
If you want only own enumerable properties (basically non-prototype chain properties) you can change it to iterate using Object.keys
and a for...of
loop instead:
//your object
var o = {
foo:"bar",
arr:[1,2,3],
subo: {
foo2:"bar2"
}
};
function* traverse(o,func) {
for (var i of Object.keys(o)) {
yield [i,o[i]];
if (o[i] !== null && typeof(o[i])=="object") {
//going one step down in the object tree!!
yield* traverse(o[i],func);
}
}
}
//that's all... no magic, no bloated framework
for(var [key, value] of traverse(o)) {
console.log(key, value);
}
//your object
var o = {
foo:"bar",
arr:[1,2,3],
subo: {
foo2:"bar2"
}
};
function* traverse(o,func) {
for (var i in o) {
yield [i,o[i]];
if (o[i] !== null && typeof(o[i])=="object") {
//going one step down in the object tree!!
yield* traverse(o[i],func);
}
}
}
//that's all... no magic, no bloated framework
for(var [key, value] of traverse(o)) {
console.log(key, value);
}
//your object
var o = {
foo:"bar",
arr:[1,2,3],
subo: {
foo2:"bar2"
}
};
function* traverse(o,func) {
for (var i in o) {
yield [i,o[i]];
if (o[i] !== null && typeof(o[i])=="object") {
//going one step down in the object tree!!
yield* traverse(o[i],func);
}
}
}
//that's all... no magic, no bloated framework
for(var [key, value] of traverse(o)) {
console.log(key, value);
}
//your object
var o = {
foo:"bar",
arr:[1,2,3],
subo: {
foo2:"bar2"
}
};
function* traverse(o,func) {
for (var i of Object.keys(o)) {
yield [i,o[i]];
if (o[i] !== null && typeof(o[i])=="object") {
//going one step down in the object tree!!
yield* traverse(o[i],func);
}
}
}
//that's all... no magic, no bloated framework
for(var [key, value] of traverse(o)) {
console.log(key, value);
}
//your object
var o = {
foo:"bar",
arr:[1,2,3],
subo: {
foo2:"bar2"
}
};
function* traverse(o,func) {
for (var i of Object.keys(o)) {
yield [i,o[i]];
if (o[i] !== null && typeof(o[i])=="object") {
//going one step down in the object tree!!
yield* traverse(o[i],func);
}
}
}
//that's all... no magic, no bloated framework
for(var [key, value] of traverse(o)) {
console.log(key, value);
}
answered Aug 11 '17 at 6:33
John
3,9652645
3,9652645
add a comment |
add a comment |
up vote
0
down vote
My Script:
op_needed = ;
callback_func = function(val) {
var i, j, len;
results = ;
for (j = 0, len = val.length; j < len; j++) {
i = val[j];
if (i['children'].length !== 0) {
call_func(i['children']);
} else {
op_needed.push(i['rel_path']);
}
}
return op_needed;
};
Input JSON:
[
{
"id": null,
"name": "output",
"asset_type_assoc": ,
"rel_path": "output",
"children": [
{
"id": null,
"name": "output",
"asset_type_assoc": ,
"rel_path": "output/f1",
"children": [
{
"id": null,
"name": "v#",
"asset_type_assoc": ,
"rel_path": "output/f1/ver",
"children":
}
]
}
]
}
]
Function Call:
callback_func(inp_json);
Output as per my Need:
["output/f1/ver"]
add a comment |
up vote
0
down vote
My Script:
op_needed = ;
callback_func = function(val) {
var i, j, len;
results = ;
for (j = 0, len = val.length; j < len; j++) {
i = val[j];
if (i['children'].length !== 0) {
call_func(i['children']);
} else {
op_needed.push(i['rel_path']);
}
}
return op_needed;
};
Input JSON:
[
{
"id": null,
"name": "output",
"asset_type_assoc": ,
"rel_path": "output",
"children": [
{
"id": null,
"name": "output",
"asset_type_assoc": ,
"rel_path": "output/f1",
"children": [
{
"id": null,
"name": "v#",
"asset_type_assoc": ,
"rel_path": "output/f1/ver",
"children":
}
]
}
]
}
]
Function Call:
callback_func(inp_json);
Output as per my Need:
["output/f1/ver"]
add a comment |
up vote
0
down vote
up vote
0
down vote
My Script:
op_needed = ;
callback_func = function(val) {
var i, j, len;
results = ;
for (j = 0, len = val.length; j < len; j++) {
i = val[j];
if (i['children'].length !== 0) {
call_func(i['children']);
} else {
op_needed.push(i['rel_path']);
}
}
return op_needed;
};
Input JSON:
[
{
"id": null,
"name": "output",
"asset_type_assoc": ,
"rel_path": "output",
"children": [
{
"id": null,
"name": "output",
"asset_type_assoc": ,
"rel_path": "output/f1",
"children": [
{
"id": null,
"name": "v#",
"asset_type_assoc": ,
"rel_path": "output/f1/ver",
"children":
}
]
}
]
}
]
Function Call:
callback_func(inp_json);
Output as per my Need:
["output/f1/ver"]
My Script:
op_needed = ;
callback_func = function(val) {
var i, j, len;
results = ;
for (j = 0, len = val.length; j < len; j++) {
i = val[j];
if (i['children'].length !== 0) {
call_func(i['children']);
} else {
op_needed.push(i['rel_path']);
}
}
return op_needed;
};
Input JSON:
[
{
"id": null,
"name": "output",
"asset_type_assoc": ,
"rel_path": "output",
"children": [
{
"id": null,
"name": "output",
"asset_type_assoc": ,
"rel_path": "output/f1",
"children": [
{
"id": null,
"name": "v#",
"asset_type_assoc": ,
"rel_path": "output/f1/ver",
"children":
}
]
}
]
}
]
Function Call:
callback_func(inp_json);
Output as per my Need:
["output/f1/ver"]
edited Feb 28 '17 at 13:40
answered Feb 28 '17 at 13:32
Mohideen ibn Mohammed
6,89934758
6,89934758
add a comment |
add a comment |
up vote
0
down vote
var test = {
depth00: {
depth10: 'string'
, depth11: 11
, depth12: {
depth20:'string'
, depth21:21
}
, depth13: [
{
depth22:'2201'
, depth23:'2301'
}
, {
depth22:'2202'
, depth23:'2302'
}
]
}
,depth01: {
depth10: 'string'
, depth11: 11
, depth12: {
depth20:'string'
, depth21:21
}
, depth13: [
{
depth22:'2201'
, depth23:'2301'
}
, {
depth22:'2202'
, depth23:'2302'
}
]
}
, depth02: 'string'
, dpeth03: 3
};
function traverse(result, obj, preKey) {
if(!obj) return ;
if (typeof obj == 'object') {
for(var key in obj) {
traverse(result, obj[key], (preKey || '') + (preKey ? '[' + key + ']' : key))
}
} else {
result.push({
key: (preKey || '')
, val: obj
});
}
return result;
}
document.getElementById('textarea').value = JSON.stringify(traverse(, test), null, 2);
<textarea style="width:100%;height:600px;" id="textarea"></textarea>
made it to submit form enctype applicatioin/json
– seung
Nov 24 '17 at 12:39
add a comment |
up vote
0
down vote
var test = {
depth00: {
depth10: 'string'
, depth11: 11
, depth12: {
depth20:'string'
, depth21:21
}
, depth13: [
{
depth22:'2201'
, depth23:'2301'
}
, {
depth22:'2202'
, depth23:'2302'
}
]
}
,depth01: {
depth10: 'string'
, depth11: 11
, depth12: {
depth20:'string'
, depth21:21
}
, depth13: [
{
depth22:'2201'
, depth23:'2301'
}
, {
depth22:'2202'
, depth23:'2302'
}
]
}
, depth02: 'string'
, dpeth03: 3
};
function traverse(result, obj, preKey) {
if(!obj) return ;
if (typeof obj == 'object') {
for(var key in obj) {
traverse(result, obj[key], (preKey || '') + (preKey ? '[' + key + ']' : key))
}
} else {
result.push({
key: (preKey || '')
, val: obj
});
}
return result;
}
document.getElementById('textarea').value = JSON.stringify(traverse(, test), null, 2);
<textarea style="width:100%;height:600px;" id="textarea"></textarea>
made it to submit form enctype applicatioin/json
– seung
Nov 24 '17 at 12:39
add a comment |
up vote
0
down vote
up vote
0
down vote
var test = {
depth00: {
depth10: 'string'
, depth11: 11
, depth12: {
depth20:'string'
, depth21:21
}
, depth13: [
{
depth22:'2201'
, depth23:'2301'
}
, {
depth22:'2202'
, depth23:'2302'
}
]
}
,depth01: {
depth10: 'string'
, depth11: 11
, depth12: {
depth20:'string'
, depth21:21
}
, depth13: [
{
depth22:'2201'
, depth23:'2301'
}
, {
depth22:'2202'
, depth23:'2302'
}
]
}
, depth02: 'string'
, dpeth03: 3
};
function traverse(result, obj, preKey) {
if(!obj) return ;
if (typeof obj == 'object') {
for(var key in obj) {
traverse(result, obj[key], (preKey || '') + (preKey ? '[' + key + ']' : key))
}
} else {
result.push({
key: (preKey || '')
, val: obj
});
}
return result;
}
document.getElementById('textarea').value = JSON.stringify(traverse(, test), null, 2);
<textarea style="width:100%;height:600px;" id="textarea"></textarea>
var test = {
depth00: {
depth10: 'string'
, depth11: 11
, depth12: {
depth20:'string'
, depth21:21
}
, depth13: [
{
depth22:'2201'
, depth23:'2301'
}
, {
depth22:'2202'
, depth23:'2302'
}
]
}
,depth01: {
depth10: 'string'
, depth11: 11
, depth12: {
depth20:'string'
, depth21:21
}
, depth13: [
{
depth22:'2201'
, depth23:'2301'
}
, {
depth22:'2202'
, depth23:'2302'
}
]
}
, depth02: 'string'
, dpeth03: 3
};
function traverse(result, obj, preKey) {
if(!obj) return ;
if (typeof obj == 'object') {
for(var key in obj) {
traverse(result, obj[key], (preKey || '') + (preKey ? '[' + key + ']' : key))
}
} else {
result.push({
key: (preKey || '')
, val: obj
});
}
return result;
}
document.getElementById('textarea').value = JSON.stringify(traverse(, test), null, 2);
<textarea style="width:100%;height:600px;" id="textarea"></textarea>
var test = {
depth00: {
depth10: 'string'
, depth11: 11
, depth12: {
depth20:'string'
, depth21:21
}
, depth13: [
{
depth22:'2201'
, depth23:'2301'
}
, {
depth22:'2202'
, depth23:'2302'
}
]
}
,depth01: {
depth10: 'string'
, depth11: 11
, depth12: {
depth20:'string'
, depth21:21
}
, depth13: [
{
depth22:'2201'
, depth23:'2301'
}
, {
depth22:'2202'
, depth23:'2302'
}
]
}
, depth02: 'string'
, dpeth03: 3
};
function traverse(result, obj, preKey) {
if(!obj) return ;
if (typeof obj == 'object') {
for(var key in obj) {
traverse(result, obj[key], (preKey || '') + (preKey ? '[' + key + ']' : key))
}
} else {
result.push({
key: (preKey || '')
, val: obj
});
}
return result;
}
document.getElementById('textarea').value = JSON.stringify(traverse(, test), null, 2);
<textarea style="width:100%;height:600px;" id="textarea"></textarea>
var test = {
depth00: {
depth10: 'string'
, depth11: 11
, depth12: {
depth20:'string'
, depth21:21
}
, depth13: [
{
depth22:'2201'
, depth23:'2301'
}
, {
depth22:'2202'
, depth23:'2302'
}
]
}
,depth01: {
depth10: 'string'
, depth11: 11
, depth12: {
depth20:'string'
, depth21:21
}
, depth13: [
{
depth22:'2201'
, depth23:'2301'
}
, {
depth22:'2202'
, depth23:'2302'
}
]
}
, depth02: 'string'
, dpeth03: 3
};
function traverse(result, obj, preKey) {
if(!obj) return ;
if (typeof obj == 'object') {
for(var key in obj) {
traverse(result, obj[key], (preKey || '') + (preKey ? '[' + key + ']' : key))
}
} else {
result.push({
key: (preKey || '')
, val: obj
});
}
return result;
}
document.getElementById('textarea').value = JSON.stringify(traverse(, test), null, 2);
<textarea style="width:100%;height:600px;" id="textarea"></textarea>
answered Nov 24 '17 at 12:34
seung
11
11
made it to submit form enctype applicatioin/json
– seung
Nov 24 '17 at 12:39
add a comment |
made it to submit form enctype applicatioin/json
– seung
Nov 24 '17 at 12:39
made it to submit form enctype applicatioin/json
– seung
Nov 24 '17 at 12:39
made it to submit form enctype applicatioin/json
– seung
Nov 24 '17 at 12:39
add a comment |
up vote
-1
down vote
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)
});
}
}
why downvoted? can someone explain it?
– Asqan
Sep 29 '15 at 10:01
add a comment |
up vote
-1
down vote
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)
});
}
}
why downvoted? can someone explain it?
– Asqan
Sep 29 '15 at 10:01
add a comment |
up vote
-1
down vote
up vote
-1
down vote
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)
});
}
}
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)
});
}
}
answered Jul 31 '15 at 8:06
Asqan
1,93663466
1,93663466
why downvoted? can someone explain it?
– Asqan
Sep 29 '15 at 10:01
add a comment |
why downvoted? can someone explain it?
– Asqan
Sep 29 '15 at 10:01
why downvoted? can someone explain it?
– Asqan
Sep 29 '15 at 10:01
why downvoted? can someone explain it?
– Asqan
Sep 29 '15 at 10:01
add a comment |
up vote
-1
down vote
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)
add a comment |
up vote
-1
down vote
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)
add a comment |
up vote
-1
down vote
up vote
-1
down vote
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)
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)
edited May 23 '17 at 12:34
Community♦
11
11
answered Aug 6 '15 at 17:44
Ricky
14.4k42725
14.4k42725
add a comment |
add a comment |
up vote
-1
down vote
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>);
}
add a comment |
up vote
-1
down vote
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>);
}
add a comment |
up vote
-1
down vote
up vote
-1
down vote
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>);
}
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>);
}
answered Jun 21 '16 at 12:27
RAJ KADAM
1
1
add a comment |
add a comment |
up vote
-1
down vote
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
withid === 1
findAll(rootObj, 'children', { id: 1 })
to find all objects
withid === 1
findAndDeleteFirst(rootObj, 'children', { id: 1 })
to delete first matching object
findAndDeleteAll(rootObj, 'children', { id: 1 })
to delete all matching objects
replacementObj
is used as the last parameter in two last methods:
findAndModifyFirst(rootObj, 'children', { id: 1 }, { id: 2, name: 'newObj'})
to change first found object withid === 1
to the{ id: 2, name: 'newObj'}
findAndModifyAll(rootObj, 'children', { id: 1 }, { id: 2, name: 'newObj'})
to change all objects withid === 1
to the{ id: 2, name: 'newObj'}
add a comment |
up vote
-1
down vote
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
withid === 1
findAll(rootObj, 'children', { id: 1 })
to find all objects
withid === 1
findAndDeleteFirst(rootObj, 'children', { id: 1 })
to delete first matching object
findAndDeleteAll(rootObj, 'children', { id: 1 })
to delete all matching objects
replacementObj
is used as the last parameter in two last methods:
findAndModifyFirst(rootObj, 'children', { id: 1 }, { id: 2, name: 'newObj'})
to change first found object withid === 1
to the{ id: 2, name: 'newObj'}
findAndModifyAll(rootObj, 'children', { id: 1 }, { id: 2, name: 'newObj'})
to change all objects withid === 1
to the{ id: 2, name: 'newObj'}
add a comment |
up vote
-1
down vote
up vote
-1
down vote
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
withid === 1
findAll(rootObj, 'children', { id: 1 })
to find all objects
withid === 1
findAndDeleteFirst(rootObj, 'children', { id: 1 })
to delete first matching object
findAndDeleteAll(rootObj, 'children', { id: 1 })
to delete all matching objects
replacementObj
is used as the last parameter in two last methods:
findAndModifyFirst(rootObj, 'children', { id: 1 }, { id: 2, name: 'newObj'})
to change first found object withid === 1
to the{ id: 2, name: 'newObj'}
findAndModifyAll(rootObj, 'children', { id: 1 }, { id: 2, name: 'newObj'})
to change all objects withid === 1
to the{ id: 2, name: 'newObj'}
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
withid === 1
findAll(rootObj, 'children', { id: 1 })
to find all objects
withid === 1
findAndDeleteFirst(rootObj, 'children', { id: 1 })
to delete first matching object
findAndDeleteAll(rootObj, 'children', { id: 1 })
to delete all matching objects
replacementObj
is used as the last parameter in two last methods:
findAndModifyFirst(rootObj, 'children', { id: 1 }, { id: 2, name: 'newObj'})
to change first found object withid === 1
to the{ id: 2, name: 'newObj'}
findAndModifyAll(rootObj, 'children', { id: 1 }, { id: 2, name: 'newObj'})
to change all objects withid === 1
to the{ id: 2, name: 'newObj'}
edited Feb 14 '17 at 13:50
answered Feb 14 '17 at 13:15
dominik791
26518
26518
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f722668%2ftraverse-all-the-nodes-of-a-json-object-tree-with-javascript%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown