Lodash returns an array of values ​​if the path is valid

I have the following lodash objects and requests in Node.js (I just run 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 valid?

Example:

 > _.get(obj, "a[].b[].c") ['apple', 'pineapple'] 
+5
source share
3 answers

As @Tomalak explained 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' ] 
+1
source

I do not know if this will be the most efficient or what you need, but can you use _.each or _.map to create an array if some conditions are valid? maybe something like

 let first = _.map(object, (item) => { //change logic for maybe if(item.bc) { return item.bc } }) //filter out nulls let second = _.without(first, null) 
0
source

The following function may help without using any additional libraries.

 function getall(input, path = "", accumulator = []) { path = path.split("."); const head = path.shift(); if (input && input[head] !== undefined) { if (!path.length) { accumulator.push(input[head]); } else if (Array.isArray(input[head])) { input[head].forEach(el => { getall(el, path.join('.'), accumulator); }); } else { getall(input[head], path.join('.'), accumulator); } } return accumulator; } 

samples

 > getall(obj, 'a.b') [ [ { c: 'apple' }, { d: 'not apple' }, { c: 'pineapple' } ] ] > getall(obj, 'abc') [ 'apple', 'pineapple' ] > getall(obj, 'abd') [ 'not apple' ] > getall(obj, 'abe') [] 
0
source

Source: https://habr.com/ru/post/1271334/


All Articles