gpt4 book ai didi

javascript - Typescript:相当于 linq .GroupBy(key => key.IdItem).Select(item => item.Single());

转载 作者:行者123 更新时间:2023-12-01 02:02:28 25 4
gpt4 key购买 nike

我正在尝试从 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];
});

我做错了什么?

最佳答案

你可以这样尝试——

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;
}
}

关于javascript - Typescript:相当于 linq .GroupBy(key => key.IdItem).Select(item => item.Single());,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50442629/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com