Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash return array of values if the path is valid

I have the following object and lodash "queries" in Node.js (I'm simply running node in the terminal):

var obj = {
  a: [{
    b: [{
      c: "apple"
    },
    {
      d: "not apple"
    },
    {
      c: "pineapple"
    }]
  }]
};

> _.get(obj, "a[0].b[0].c")
'apple'

> _.get(obj, "a[0].b[1].c")
undefined

> _.get(obj, "a[0].b[2].c")
'pineapple'

My question is: is there a way to return an array of values where the path was found to be valid?

Example:

> _.get(obj, "a[].b[].c")
['apple', 'pineapple']
like image 324
Letokteren Avatar asked Aug 29 '17 14:08

Letokteren


1 Answers

As @Tomalak has suggested in a comment, the solution was to use JSONPath instead of Lodash.

Their github page: https://github.com/dchester/jsonpath

Example:

> var jp = require("jsonpath")
> var obj = {
   a: [{
     b: [{
       c: "apple"
     },
     {
       d: "not apple"
     },
     {
       c: "pineapple"
     }]
   }]
 };

> jp.query(obj, "$.a[*].b[*].c")
[ 'apple', 'pineapple' ]
like image 186
Letokteren Avatar answered Oct 15 '22 22:10

Letokteren