我有两个列表,我想通过比较两个列表来创建一个新列表,并且新列表应仅包含每个列表中包含的那些元素。
List1=[[id: 1, label: 'cocoa'],[id: 2, label: 'apple'],[id: 3, label: 'cherry'],[id: 4, label: 'banana'],[id: 5, label: 'melon'],[id: 6, label: 'orange'],[id: 7, label: 'pineapple'],[id: 8], label: 'strawberry']
List2=[2,5,7,8]
expectedList = [[id: 2, label: 'apple'],[id: 5, label: 'melon'],[id: 7, label: 'pineapple'],[id: 8], label: 'strawberry']]
实际代码如下:
"options": [
{
"id": 58,
"label": "cocoa",
"swatch_value": null,
"products": [
118
]
},
{
"id": 59,
"label": "dark chocolate",
"swatch_value": null,
"products": [
120,
127
]
},
{
"id": 60,
"label": "apple",
"swatch_value": null,
"products": [
121,
128
]
},
{
"id": 61,
"label": "milk",
"swatch_value": null,
"products": [
122
]
},
{
"id": 62,
"label": "coconut",
"swatch_value": null,
"products": [
130
]
},
{
"id": 65,
"label": "cherry",
"swatch_value": null,
"products": [
126
]
}
]
因此,第一个列表将包含上面的json,第二个列表将包含下面的数字,这些数字等于某些ID。
List<int> secondList = [58, 59, 60, 61];
现在,当我想通过将secondList与第一个列表的ID进行比较来生成新列表时,第三个列表为空。
List thirdList = firstList.options.where((element) => secondList.contains(element.id)).toList();
var list1 = [1,2,3,4,5,6,7,8];
var list2 = [2,5,7,8];
var expectedList = list1.toSet().intersection(list2.toSet()).toList();
print(expectedList.toString());
更多信息在这里。
尊重您的信息:
var dataList = data['options'];
var firstList = List<int>.generate(dataList.length, (i) => dataList[i]['id']);
var secondList = [58, 59, 60, 61];
var thirdList = firstList.toSet().intersection(secondList.toSet()).toList();
var filtered = dataList.where((e) => thirdList.contains(e['id'])).toList();
print(filtered.toString());
哪里:
const data = {
"options": [
...
]
};
结果是:
[{id: 58, label: cocoa, swatch_value: null, products: [118]}, {id: 59, label: dark chocolate, swatch_value: null, products: [120, 127]}, {id: 60, label: apple, swatch_value: null, products: [121, 128]}, {id: 61, label: milk, swatch_value: null, products: [122]}]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句