Filtering JSON

P

Peter May

I have a simple JSON:

var j = '{
"result": "1",
"get": [
{
"type": "test",
"more": {
"type": "test1",
},
"more2": {
"qwe": "test2",
"email": null,
},
"more3": null
},
{
"type": "best",
"more": {
"type": "test11",
},
"more2": {
"qwe": "test22",
"email": null,
},
"more3": null
},
]
}';

var res = JSON.parse(j);
var search_value = 'test22'; // for example search text

I want to filter (in the above example) array in object "get" that the
final result will only leave this objects that contains any property
which have a search_value text.

In above example the final result will be:

var results = {
"result": "1",
"get": [
{
"type": "best",
"more": {
"type": "test11",
},
"more2": {
"qwe": "test22",
"email": null,
},
"more3": null
},
]
};

I can do this using for-in loop, but if there will be more objects in
object then building every time a new for-in loop is not a good idea,
for me.

The question is: is there a way to iterate all objects (using one
method) and find only that objects which contains search_value in any
property?
 
T

Thomas 'PointedEars' Lahn

Peter said:
I have a simple JSON:

What you have there is _not_ JSON.
var j = '{

The apostrophe surely does not belong here …
"result": "1",
"get": [
{
"type": "test",
"more": {
"type": "test1",
},
"more2": {
"qwe": "test2",
"email": null,
},
"more3": null
},
{
"type": "best",
"more": {
"type": "test11",
},
"more2": {
"qwe": "test22",
"email": null,
},
"more3": null
},
]
}';

… or there.
var res = JSON.parse(j);
var search_value = 'test22'; // for example search text

Assuming this could work …
I want to filter (in the above example) array in object "get" that the
final result will only leave this objects that contains any property
which have a search_value text.

In above example the final result will be:

var results = {
"result": "1",
"get": [
{
"type": "best",
"more": {
"type": "test11",
},
"more2": {
"qwe": "test22",
"email": null,
},
"more3": null
},
]
};

I can do this using for-in loop, but if there will be more objects in
object then building every time a new for-in loop is not a good idea,
for me.

… correct.
The question is: is there a way to iterate all objects (using one
method) and find only that objects which contains search_value in any
property?

Yes. What have you tried so far?


PointedEars
 
D

dhtml

I have a simple JSON:

var j = '{ .............^
     "result": "1",

LineTerminator in a string literal is a SyntaxError..

| var j = '{


This works:
var search_value = 'test22'; // for example search text

This does not work:
// SyntaxError
var search_value = 'test
22';
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top