I'm stuck in mapping object to array. I use map, but its add every object field in array and i got a lot of undefined.
const mapKey: { [key: string]: number } = { 'hello': 3, }; preferences = { hello: true, ..... ..... } const array = Object.entries(preferences).map(([key, value]) => { return mapKey[key] && { index: mapKey[key], visible: true }; });
result is:
[undefined, undefined....{ index: mapKey[key], visible: true }] but i need just [{ index: mapKey[key], visible: true }]
The Array#map
method generates an array based on return value, it's not suited for requirement so use Array#reduce
method.
const array = Object.entries(preferences).reduce((arr, [key, value]) => {
// push into the array only if defined
columnIndexMap[key] && arr.push({ index: mapKey[key], visible: true });
// return the array reference for next iteration
return arr;
// set initial value as empty array for the result
}, []);
One-liner solution:
const array = Object.entries(preferences).reduce((arr, [key, value]) => (columnIndexMap[key] && arr.push({ index: mapKey[key], visible: true }), arr), []);
The answer with reduce
of course works and is efficient. You can also use filter()
+ map
. This has the disadvantage of looking at values twice, but has a readability advantage. Which is more important, of course, depends on your use-case. I would prefer the following unless there is so much data that the additional work is noticeable:
const mapKey = { 'hello': 3, 'test':4, 'test2': 5}; let preferences = { hello: true, test:false, test2:true} let filtered = Object.entries(preferences) .filter(([k, visible]) => visible) .map(([k, visible]) => ({ index: mapKey[k], visible })) console.log(filtered)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.