ishan
ishan

Reputation: 1

Filtering child collections using lodash javascript

I have a service which return following JSON

  'data':     [{
    'category': {

        'Questions': [{
            aswers: [{
                Text: 'Text1'
            }],
            Data: 'TT'
        }],
        name: 'name1'
    }

}, {
    'category': {

        'Questions': [{
            aswers: [{
                Text: 'Text1'
            }],
            Data: 'TT'
        }],
        name: 'name1'
    }

}, {
    'category': {

        'Questions': [{
            aswers: [{
                Text: 'Text1'
            }],
            Data: 'TT'
        }],
        name: 'name1'
    }

}]

I want to write a filter query using lodash based on parent collection and child collections.

where category.Questions.data=='xxx' and category.Questions.aswers.Text='ddd'

i tried below query

var x=  _.filter(data.category, {Questions: [{Data: 'xxx', 'Questions.aswers.Text':'ddd'}] });

after that i want to update the value of the answer.Text selected objects.

relations ship is data has collections of category objects category object have collection of answers objects answers object have collection of text objects

How can i achieve this?

Upvotes: 0

Views: 644

Answers (1)

Antonio Narkevich
Antonio Narkevich

Reputation: 4326

this is a bit tricky but here's how you can do it.

let matchingQuestions = _.chain(jsonData.data)
   .map(d => d.category.Questions) //So we have array of Questions arrays
   .flatten() //Now we have a single array with all Questions
   .filter({Data: 'xxx'}) //Filtering by Data
   .map('aswers') //After this we will have an array of answers arrays
                  //(only answers with matching Data definitely)
   .flatten() //A single array with all answers
   .filter({Text: 'ddd'}) //Now filtering by Text
   .value(); //Unwrapping lodash chain to get the result

   //Now you can update them however you want
   _.each(matchingQuestions, q => q.Text = 'Updated Text');

Here's a jsbin with working example. I used lodash v4.

Upvotes: 1

Related Questions