[英]How can I loop through an object with a specific condition and return an array of its values?
I have an array of all items ids:我有一个包含所有项目 ID 的数组:
const allIds = ['a1gb', 'f4qa', 'i9w9']
I also have an object with it's properties having those ids as keys:我还有一个对象,它的属性以这些 id 作为键:
const byId = {
a1gb: {
whatever1
},
anyOtherIdThatIDontNeed: {
whatever444
},
f4qa: {
whatever2
},
i9w9: {
whatever3
}
}
What is the most common way to return an array that would look like返回看起来像的数组的最常见方法是什么
[ { whatever1 }, { whatever2 }, { whatever3 } ]
and skip the Ids I don't want in my final array?并在我的最终数组中跳过我不想要的 ID?
This a log of the array with the ids:这是带有 id 的数组日志:
This is a log of the object from which I need to return an array with the values of the keys from that array of ids skipping the ones I don't need:这是一个对象的日志,我需要从中返回一个数组,其中包含该 id 数组中的键值,跳过我不需要的那些:
PS Problem is that in that return array from the map function I get undefined when it encounters "anyOtherIdThatIDontNeed:". PS 问题是,在 map 函数的返回数组中,当它遇到“anyOtherIdThatIDontNeed:”时,我得到了未定义。
PPS[ ANSWER ] - The array of Ids had ids that do not match object's keys and that is why I was getting undefined. PPS[ 答案 ] - ID 数组的 ID 与对象的键不匹配,这就是我未定义的原因。
var result = allids.map(val => ({byId[val]}))
I would suggest this way, try the below code if the array also has unwanted ids.我会建议这样,如果数组也有不需要的 ID,请尝试下面的代码。
var result = allids.map(val => ({byId[val]})).filter(val => val?true:false)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.