Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
548 views
in Technique[技术] by (71.8m points)

javascript - 如何遍历具有特定条件的对象并返回其值的数组?(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的数组的日志:)

具有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问题是,在映射函数的返回数组中,当遇到“ 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 [ANSWER]-ID数组的ID与对象的键不匹配,这就是为什么我不确定的原因。)

  ask by Mihai Ciobanu translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

var result = allids.map(val => ({byId[val]}))

我建议采用这种方式,如果数组也有不需要的ID,请尝试以下代码。

var result = allids.map(val => ({byId[val]})).filter(val => val?true:false)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...