Javascript 如果密钥存在,则将其包含到数组中

Javascript 如果密钥存在,则将其包含到数组中,javascript,dictionary,transform,Javascript,Dictionary,Transform,我一直在把对象映射到数组。 我使用map,但它将数组中的每个对象字段相加,我得到了很多未定义的字段 const-mapKey:{[key:string]:number}={ “你好”:3, }; 首选项={ 你好:是的, ..... ..... } 常量数组=Object.entries(preferences).map([key,value])=>{ 返回mapKey[key]&&{index:mapKey[key],可见:true}; }); 该方法基于返回值生成一个数组,它不适合要求,所

我一直在把对象映射到数组。 我使用map,但它将数组中的每个对象字段相加,我得到了很多未定义的字段

const-mapKey:{[key:string]:number}={
“你好”:3,
};
首选项={
你好:是的,
.....
.....
}
常量数组=Object.entries(preferences).map([key,value])=>{
返回mapKey[key]&&{index:mapKey[key],可见:true};
});
该方法基于返回值生成一个数组,它不适合要求,所以请使用该方法

一套解决方案:

const array = Object.entries(preferences).reduce((arr, [key, value]) => (columnIndexMap[key] && arr.push({ index: mapKey[key], visible: true }), arr), []);

使用
reduce
的答案当然有效。您还可以使用+
map
。这有两次查看值的缺点,但具有可读性优势。当然,哪个更重要取决于您的用例。我更喜欢以下内容,除非有太多的数据,额外的工作是显而易见的:

const-mapKey={'hello':3,'test':4,'test2':5};
让首选项={hello:true,test:false,test2:true}
let filtered=Object.entries(首选项)
.filter(([k,可见])=>可见)
.map(([k,visible])=>({index:mapKey[k],visible}))
console.log(已过滤)
const array = Object.entries(preferences).reduce((arr, [key, value]) => (columnIndexMap[key] && arr.push({ index: mapKey[key], visible: true }), arr), []);