[英]JS if key exist, include to array
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.
我使用map,但是它在数组中添加了每个对象字段,所以我有很多未定义的地方。
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. Array#map
方法根据返回值生成一个数组,它不适合要求,因此请使用Array#reduce
方法。
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. reduce
课程的答案当然有效。 You can also use filter()
+ map
. 您还可以使用
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.