我有一个JSON文件,其中包含我需要过滤的数据。
json是这个示例结构:
[{A:"data", C:"flightData", D:"FlightData"},
{B:"data", C:"flightData", D:"FlightData"},
{A:"data", C:"flightData", D:"FlightData"},
{B:"data", C:"flightData"},
{A:"data", C:"flightData", D:"FlightData"},
{B:"data", D:"FlightData"}]
我正在按方法分组
function groupBy(list, keyGetter) {
const map = new Map();
list.forEach((item) => {
const key = keyGetter(item);
const collection = map.get(key);
if (!collection) {
map.set(key, [item]);
} else {
collection.push(item);
}
});
return map;
}
首先,我按A或B分组为数组
A is [[C],[D]]
和B is[[C],[D]]
但是,如果数据中没有C或D,则由于不需要数据,我需要删除该组。
for (let value of s1) {
// A or B
const routeGrouped = groupBy(PriceArrayFinal, route =>
route.FinalArrival);
for (let origin of s3) {
// C or D
const originGrouped = groupBy(routeGrouped.get(value), route =>
route.FirstDepartCityName);
如果C或D不存在,是否可以删除整个组,例如A:[ [C], [] ]
。如果有一个空数组,我需要删除A或B组吗?
编辑:预期输出:A或B的所有组都具有C和D
[{A:"data", C:"flightData", D:"FlightData"},
{B:"data", C:"flightData", D:"FlightData"},
{A:"data", C:"flightData", D:"FlightData"},
{A:"data", C:"flightData", D:"FlightData"}]
[ [ [Array], [Array] ], [ [Array], [Array] ] ,[ [Array], [Array] ], [ [Array], [Array] ] ]
答案 0 :(得分:1)
如果要获取所有具有C
&& D
值的对象,则可以像这样使用filter
:
let input=[{A:"data",C:"flightData",D:"FlightData"},{B:"data",C:"flightData",D:"FlightData"},{A:"data",C:"flightData",D:"FlightData"},{B:"data",C:"flightData"},{A:"data",C:"flightData",D:"FlightData"},{B:"data",D:"FlightData"}];
let output = input.filter(({ C, D }) => C && D);
console.log(output)
答案 1 :(得分:0)
使用数组filter()方法。
const arr = [{A:"data", C:"flightData", D:"FlightData"},
{B:"data", C:"flightData", D:"FlightData"},
{A:"data", C:"flightData", D:"FlightData"},
{B:"data", C:"flightData"},
{A:"data", C:"flightData", D:"FlightData"},
{B:"data", D:"FlightData"}];
const result = arr.filter(a => {
return (a.hasOwnProperty('A') || a.hasOwnProperty('B') && a.hasOwnProperty('C') && a.hasOwnProperty('D'));
});
console.log(result);
/* Expected Output:
[{A:"data", C:"flightData", D:"FlightData"},
{B:"data", C:"flightData", D:"FlightData"},
{A:"data", C:"flightData", D:"FlightData"},
{A:"data", C:"flightData", D:"FlightData"}]
*/