Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash - Find deep in array of object

I have an array of an object like this

[
    {
        'a': 10,
        elements: [
            {
                'prop': 'foo',
                'val': 10
            },
            {
                'prop': 'bar',
                'val': 25
            },
            {
                'prop': 'test',
                'val': 51
            }
        ]
    },
    {
        'b': 50,
        elements: [
            {
                'prop': 'foo',
                'val': 30
            },
            {
                'prop': 'bar',
                'val': 15
            },
            {
                'prop': 'test',
                'val': 60
            }
        ]
    },
]

What I need is sum the property Val when prop is foo. So, I have to search through elements and get all objects where prop is foo. With this objects, I should sum the val property.

I tried to use many combinations of _.find, _.pick and so on, but I don't get the right result. Can someone help me?

like image 919
Mistre83 Avatar asked Jan 12 '17 10:01

Mistre83


Video Answer


2 Answers

Here's a one liner solution to this problem:

const _ = require('lodash')

let deepFind = (JSONArray, keyPath, keyValue) => _.find(JSONArray, _.matchesProperty(keyPath, keyValue))

let JSONArray = [{a:1, b:2, c:{d: "cd"}}, {a:3, b:4, c:{d: "ef"}}, {a:3, b:4, c:[{d: "ef"}]} ]

console.log(deepFind(JSONArray, "c.d", "cd"))
// {a:1, b:2, c:{d: "cd"}}

console.log(deepFind(JSONArray, "b", 4)) 
//{a:3, b:4, c:{d: "ef"}}

console.log(deepFind(JSONArray, ['c', 'd'], "cd"))
//{a:1, b:2, c:{d: "cd"}}

console.log(deepFind(JSONArray, 'c[0].d' /* OR ['c', '0', 'd']*/, "ef"))
//{a:1, b:2, c:{d: "cd"}}
like image 190
Ahsan Babar Avatar answered Oct 06 '22 18:10

Ahsan Babar


Here's a solution that flattens the elements and then filters the result to get the required elements before summing the val property:

var result = _.chain(data)
    .map('elements')               // pluck all elements from data
    .flatten()                     // flatten the elements into a single array
    .filter({prop: 'foo'})         // exatract elements with a prop of 'foo'
    .sumBy('val')                  // sum all the val properties
    .value()

Chaining is a way of applying a sequence of operations to some data before returning a value. The above example uses explicit chaining but could be (maybe should be) written using implicit chaining:

var result = _(data)
    .map('elements')
    .flatten()
    .filter({prop: 'foo'})
    .sumBy('val');
like image 34
Gruff Bunny Avatar answered Oct 06 '22 20:10

Gruff Bunny