打字稿:如何按字段名称对命名对象列表的对象进行分组
Typescript : How to group an object of named list of objects by field name
我必须使用 javascript 这种美妙的语言来处理数据。
在那之前,我设法靠自己实现了我所需要的,但我在那里达到了我的极限。
很难解释我的数据是如何构建的,所以让我们做一个架构。这就是我的 :
obj: {[key: string]: {name: string, type: string}[]} =
{
"animals": [
{name: "Louis", type: "dog"},
{name: "John", type: "cat"},
{name: "Jordan", type: "dog"},
]
"cars" : [
{name: "alpha", type: "ferrari"},
{name: "beta", type: "ferrari"},
{name: "charlie", type: "mercedes"},
]
}
我尝试实现的是针对每个对象,按类型对列表中的对象进行分组。这看起来像这样:
obj: {[key: string]: {[key: string]: {name: string, type: string}[]}} =
{
"animals": {
"dog": [
{name: "Louis", type: "dog"},
{name: "Jordan", type: "dog"},
],
"cat": [
{name: "John", type: "cat"},
]
}
"cars" : {
"ferrari": [
{name: "alpha", type: "ferrari"},
{name: "beta", type: "ferrari"},
],
"mercedes": [
{name: "charlie", type: "mercedes"},
]
}
}
你知道如何实现吗?
我认为您正在寻找以下内容(因为您的问题标题中有 TypeScript):
interface Value {
name: string;
type: string;
}
type Categorized = {
[index: string]: Record<string, Value[]>;
};
const results = Object.entries(obj).reduce<Categorized>((mapping, [key, values]) => {
const group: Record<string, Value[]> = {};
for (const value of values) {
if (group[value.type] === undefined) {
group[value.type] = [value];
} else {
group[value.type].push(value);
}
}
return {
...mapping,
[key]: group,
};
}, {});
我必须使用 javascript 这种美妙的语言来处理数据。 在那之前,我设法靠自己实现了我所需要的,但我在那里达到了我的极限。
很难解释我的数据是如何构建的,所以让我们做一个架构。这就是我的 :
obj: {[key: string]: {name: string, type: string}[]} =
{
"animals": [
{name: "Louis", type: "dog"},
{name: "John", type: "cat"},
{name: "Jordan", type: "dog"},
]
"cars" : [
{name: "alpha", type: "ferrari"},
{name: "beta", type: "ferrari"},
{name: "charlie", type: "mercedes"},
]
}
我尝试实现的是针对每个对象,按类型对列表中的对象进行分组。这看起来像这样:
obj: {[key: string]: {[key: string]: {name: string, type: string}[]}} =
{
"animals": {
"dog": [
{name: "Louis", type: "dog"},
{name: "Jordan", type: "dog"},
],
"cat": [
{name: "John", type: "cat"},
]
}
"cars" : {
"ferrari": [
{name: "alpha", type: "ferrari"},
{name: "beta", type: "ferrari"},
],
"mercedes": [
{name: "charlie", type: "mercedes"},
]
}
}
你知道如何实现吗?
我认为您正在寻找以下内容(因为您的问题标题中有 TypeScript):
interface Value {
name: string;
type: string;
}
type Categorized = {
[index: string]: Record<string, Value[]>;
};
const results = Object.entries(obj).reduce<Categorized>((mapping, [key, values]) => {
const group: Record<string, Value[]> = {};
for (const value of values) {
if (group[value.type] === undefined) {
group[value.type] = [value];
} else {
group[value.type].push(value);
}
}
return {
...mapping,
[key]: group,
};
}, {});