lost9123193 lost9123193 - 3 months ago 7
Javascript Question

Filtering for Nested Property in Javascript/Lodash

I currently have data that looks like this:

[{
"id": 1,
"name": "Canada",
"checked": true
"vactionSpots": [{
"id": 1,
"name": "Toronto",
"checked":false
"activities": [{
"id": 1,
"checked": false
"name": "Niagara Falls"
}]
}, {
"id": 2,
"name": "France",
"checked":true,
"activities": [{
"id": 2,
"checked":true
"name": "Eiffel tower"
}]
}]
}, {
"id": 2,
"name": "US",
"checked": true
"vactionSpots": [{
"id": 3,
"name": "California",
"checked": true
"activities": [{
"id": 3,
"name": "Surfing",
"checked":false
}]
}]
}]


I'm gathering the activities id's from activities which have checked set to true.

so the result looks something like this:

2


While I can get this, I have to go through 3 levels before I can access activities

for (i = 0; i < country.length; i++){
country = allAreas[i];
....
for (j = 0; j < country.vacationSpots.length; j++){
....
for (k = 0; k < vacationSpots.activities.length; k++){


(Search through country, then vacationSpots, then activities. Is there a way to filter this without traversing through each level? Is there a way to do this with Lodash?

Answer
var Obj = {}; //your Object here
var Res = []; //an Array for ids to be stored in
var str = JSON.stringify(Obj);
var rgx = str.match(/"activities":‌​\[{"id":\d+,"name":".+?","checked":true}/gi);
for(i=0, l=rgx.length; i<l; i++) { Res.push(Number(rgx[i].match(/"id":(\d+)/i)[1])); }

My apologies for giving another answer initially: I thought you needed to count them, not get the ids.

P.S. I have no idea why you have objects wrapped up in arrays ([{ ... }]). You only need the curly braces to make something into an object ({ ... }). Another note: I'm using match to make the code more readable, but you could use exec and iterate over the resulting array, splicing out items you don't need. Use .indexOf( ... ) != -1 if your array is going to contain duplicates and you don't want them.