gpt4 book ai didi

javascript - 带有动态键的 TypeScript array.map()

转载 作者:行者123 更新时间:2023-12-03 08:17:57 28 4
gpt4 key购买 nike

我有一个名为 fooArrayFoo 数组,但我想 map() 该数组仅包含“key: value”对,在 arrayOfKeys 中定义。

class Foo {
id: number;
name: string;
age: number;

constructor(id: number, name: string, age: number) {
this.id = id;
this.name = name;
this.age = age;
}
}

let fooArray: Foo[] = [
new Foo(1, 'Foo', 20),
new Foo(2, 'Bar', 21),
new Foo(3, 'MyFoo', 20)
];


//The keys I would like to select from Foo.
const arrayOfKeys: (keyof Foo)[] = ['name', 'age'];

我不知道该怎么做才能得到下面想要的结果:

// The result is a copy of 'fooArray', but the objects only 
// contain the keys (and their values) defined in 'arrayOfKeys'.
[
{ name: 'Foo', age: 20 },
{ name: 'Bar', age: 21 },
{ name: 'MyFoo', age: 20 }
]

最佳答案

您可以通过在 map 中创建一个新对象并返回它来做到这一点?

类似于

const fooArrayWithLimitedKeys = fooArray.map(item => arrayOfKeys.reduce(
(accumulator, key) => {
accumulator[key] = item[key]
return accumulator
}, {})
)

它也可以不使用reduce来编写,如下所示:

const fooArrayWithLimitedKeys = fooArray.map(item => {
const returnValue = {}
arrayOfKeys.forEach(key => {
returnValue[key] = item[key]
})
return returnValue;
})

关于javascript - 带有动态键的 TypeScript array.map(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68768940/

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