I have an array of Foo called fooArray, but I would like to map() the array to only contain the “key: value” pairs which are defined in 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'];
I do not know what to do to get the desired result below:
// 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 }
]
You can probably do this by creating a new object in the map and returning it?
Something like
const fooArrayWithLimitedKeys = fooArray.map(item => arrayOfKeys.reduce(
(accumulator, key) => {
accumulator[key] = item[key]
return accumulator
}, {})
)
it can also be written without reduce like follows:
const fooArrayWithLimitedKeys = fooArray.map(item => {
const returnValue = {}
arrayOfKeys.forEach(key => {
returnValue[key] = item[key]
})
return returnValue;
})
Considering you simply want to modify each item of your array of objects to only contain desired keys, you may go like that:
const src = [
{ id: 1, name: 'Foo', age: 20 },
{ id: 2, name: 'Bar', age: 21 },
{ id: 3, name: 'MyFoo', age: 20 }
]
const keys = ['name', 'age']
const result = src.map(item => Object.assign(
...keys.map(key => ({[key]: item[key]}))
))
console.log(result)
You can use Object Destructuring, inside a map function, something like that.
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)
];
const arrayOfKeys: (keyof Foo)[] = ['name', 'age'];
const result = fooArray.map(element =>(({name,age}) => ({name,age}))(element));
console.log(result);