使用lodash javascript筛选子集合

Filtering child collections using lodash javascript

本文关键字:子集合 筛选 javascript lodash 使用      更新时间:2024-02-29

我有一个服务,它返回以下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'
    }
}]

我想使用基于父集合和子集合的lodash编写一个过滤器查询。

where类别。问题.data=="xxx"和类别。Questions.aswers.Text='dd'

我尝试了以下查询

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

之后我想更新答案的值。为所选对象添加文本。

关系船是数据具有类别对象的集合category对象具有答案对象的集合answers对象具有文本对象的集合

我怎样才能做到这一点?

这有点棘手,但以下是如何做到这一点。

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');

下面是一个带有工作示例的jsbin。我用了lodash v4。