json 如何使用typescript获取每个分组数组中的第一个记录

i1icjdpr  于 12个月前  发布在  TypeScript
关注(0)|答案(2)|浏览(207)

我有一个数组,我要做的是我需要分组,并需要在每个组的第一个元素到一个数组.我设法做分组的一部分,并努力做第二部分可以有人帮我做到这一点.
下面是我尝试的,

this.faresDataAirlineGroup = this.faresData.reduce(function (r, a) {
  r[a.AirCode] = r[a.AirCode] || [];
  r[a.AirCode].push(a);

  return r;
}, Object.create(null));

字符串
样本Json,

[
{
"RfNo": "500",
"ABaseFare": "110",
"ATax": "267.22",
"YBaseFare": "0",
"AirCode": "AF"
},
{
"RfNo": "502",
"ABaseFare": "110",
"ATax": "267.22",
"YBaseFare": "0",
"AirCode": "DD"
},
{
"RfNo": "501",
"ABaseFare": "110",
"ATax": "267.22",
"YBaseFare": "0",
"AirCode": "DD"
},
{
"RfNo": "503",
"ABaseFare": "110",
"ATax": "267.22",
"YBaseFare": "0",
"AirCode": "AF"
}
]


期望的JSON,

[
{
"RfNo": "500",
"ABaseFare": "110",
"ATax": "267.22",
"YBaseFare": "0",
"AirCode": "AF"
},
{
"RfNo": "502",
"ABaseFare": "110",
"ATax": "267.22",
"YBaseFare": "0",
"AirCode": "DD"
}
]

vom3gejh

vom3gejh1#

假设obj为 * 数组对象 *。
函数对对象进行分组

const groupByKey = (list: any[], key: string, {omitKey = false}: { omitKey: true; }) => list.reduce((hash, {[key]: value, ...rest}) => ({
...hash, [value]: (hash[value] || []).concat(omitKey ? {...rest} : {...rest})
}), {});

const groupByKey1 = groupByKey(obj, 'AirCode', {omitKey: true});

const x: any[] = [];
Object.entries(groupByKey1).forEach(
    ([key, value]) => x.push(value)
);
const z: { ABaseFare: any; ATax: any; RfNo: any; YBaseFare: any; }[] = [];
x.forEach(value => {
  const p = {
    ABaseFare: value[0].ABaseFare,
    ATax: value[0].ATax,
    RfNo: value[0].RfNo,
    YBaseFare: value[0].YBaseFare,
   };
 z.push(p);
});
console.log(z);

字符串

pnwntuvh

pnwntuvh2#

我正在寻找和你一样的 * 过滤 *。The other answer工作(谢谢!),但是我和你都不需要分组。我为我们的用例找到了一个更简单,更快的解决方案:

this.faresData.reduce((r, a) => r.some(x => x.AirCode == a.AirCode) ? r : [...r, a], []);

字符串
else的例子中,我使用spread语法来“推送”每个第一个 fare。结果包含了你所期望的json:

[
 {
  "RfNo": "500",
  "ABaseFare": "110",
  "ATax": "267.22",
  "YBaseFare": "0",
  "AirCode": "AF"
 },
 {
  "RfNo": "502",
  "ABaseFare": "110",
  "ATax": "267.22",
  "YBaseFare": "0",
  "AirCode": "DD"
 }
]

相关问题