我有一个返回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编写过滤器查询。
其中category.Questions.data =='xxx'和category.Questions.aswers.Text ='ddd'
我试过下面的查询
var x= _.filter(data.category, {Questions: [{Data: 'xxx', 'Questions.aswers.Text':'ddd'}] });
之后我想更新answer.Text选定对象的值。
关系是谁 data包含类别对象的集合 category对象有答案对象的集合 answers对象有文本对象的集合我怎样才能做到这一点?
答案 0 :(得分:1)
这有点棘手但是你可以做到这一点。
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');