[英]How can I map over two arrays and return matches as buttons?
I have an array of key words and an array of objects. 我有一系列关键词和一组对象。 The key words array matches with a title inside an object from the array of objects data.
关键字数组与对象数据数组中的对象内的标题匹配。 I want to map over all of my objects looking for a key word match and return that objects title.
我想映射所有对象,寻找关键字匹配并返回该对象标题。 I want to do this for each key word in my key word array.
我想对关键字数组中的每个关键字执行此操作。
Right now, I can only get it to work for one key word inside of the key word array. 现在,我只能让它为关键字数组中的一个关键字工作。 Basically if I have...
基本上如果我有......
keyWords = [ "sink", "tub", "brush" ]
keyWords = [“sink”,“tub”,“brush”]
And my array of objects contains an obj.title which equals these key words, it will only match one of them and will return one button named "sink". 我的对象数组包含一个等于这些关键词的obj.title,它只匹配其中一个,并返回一个名为“sink”的按钮。
I can't seem to iterate through all of my key words array, but I am iterating through my array of objects. 我似乎无法遍历所有关键字数组,但我正在迭代我的对象数组。
data = array of objects
data =对象数组
keyWords = array of key words
keyWords =关键词数组
The goal is to map over data looking for matches in my key words, if I find a match I want to return a button with the matched objects title. 我的目标是在我的关键词中映射寻找匹配项的数据,如果我找到匹配项,我想返回一个带有匹配对象标题的按钮。 The problem with this is that it doesn't iterate over the keyWords array.
这个问题是它不会遍历keyWords数组。 If I add something like keyWords[0] I can look at that specific item for a match, but I want to iterate over all of the keywords and find all matches.
如果我添加类似keyWords [0]的东西,我可以查看匹配的特定项目,但我想迭代所有关键字并找到所有匹配项。
const renderKeyButtons = this.props.data.filter(obj => {
return this.state.keyWords === obj.title;
}).map((obj, idx) => {
return (
<button key={idx}>{obj.title}</button>
);
});
My guess is that I need to add something to map over the keywords, like an additional (map, idx) => function but I'm not sure how to do this AND return all of the buttons at once. 我的猜测是我需要添加一些内容来映射关键字,比如一个额外的(map,idx)=>函数,但我不知道如何做到这一点并立即返回所有按钮。
Use Array.prototype.includes()
method to achieve it without any iteration like this 使用
Array.prototype.includes()
方法来实现它,而不需要像这样的任何迭代
const renderKeyButtons = this.props.data.filter(obj => {
return this.state.keyWords.includes(obj.title);
}).map((obj, idx) => {
return (
<button key={idx}>{obj.title}</button>
);
});
You are trying to compare an array to a string. 您正在尝试将数组与字符串进行比较。 Use
Array#includes()
to see if string is in array 使用
Array#includes()
查看string是否在数组中
const renderKeyButtons = this.props.data.filter(obj => {
return this.state.keyWords.includes(obj.title);
}).map((obj, idx) => {
return (
<button key={idx}>{obj.title}</button>
);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.