打字稿:等价的linq .GroupBy(key => key.IdItem).Select(item => item.Single());

时间:2018-05-21 05:43:52

标签: javascript linq typescript

我正在尝试从linq到typescript等效.GroupBy(key => key.IdItem).Select(item => item.Single());

我尝试了什么:

let parents = value.reduce((parents, parent) => ({
            ...ubc,
            [parent.IdItem]: [...(parents[u.IdItem] || []), parent],
        }), {}) as Array<ItemsViewModel>;


Array.prototype.map.call(parents, parent => {
    if (parents.length > 1) {
        throw new Error('The input sequence contains more than one element');
    }
    else if (!parents.length) {
        throw new Error('The input sequence is empty');
    }
    return parent[0];
});

我做错了什么?

1 个答案:

答案 0 :(得分:2)

你可以这样试试 -

let parentsById = 
  value.reduce((dict, parent) => {
    let { IdItem } = parent;

    dict[IdItem] = dict[IdItem] || [];
    dict[IdItem].push(parent);
    return dict;
    }, {});

let result = 
  Object.keys(parentsById)
    .map(k => {
      let parents = parentsById[k];
      if(parents.length !== 1) { throw new Error("Must contain a single item"); }
      return parents[0];
      });

此外,如果您只想要独特的父母,您可以使用看见ID的哈希 -

let result = [];
let seenIds = {};

for(let parent of value) {
  let { IdItem } = parent;
  if(!seenIds[IdItem]) {
    result.push(parent);
    seenIds[IdItem] = true;
  }
}