gpt4 book ai didi

javascript - 如何找到包含这些ID的数组元素?

转载 作者:行者123 更新时间:2023-11-28 17:07:50 25 4
gpt4 key购买 nike

这是一个逻辑问题。我很努力,但就是无法解决!

例如。我有一个数组:["tech", "review", "howto"] 。我还有另一个包含 id 和文本的巨大数组。 👇

[
{ id: "tech", text: "Technology" },
{ id: "fin", text: "Finance" },
{ id: "digimark", text: "Digital Marketing" },
{ id: "coding", text: "Programming" },
{ id: "tutorial", text: "Tutorial" },
{ id: "howto", text: "How To" },
{ id: "writing", text: "Writing" },
{ id: "inspire", text: "Inspirational" },
{ id: "science", text: "Science" },
{ id: "politics", text: "Politics" },
{ id: "lifestyle", text: "Lifestyle" },
{ id: "food", text: "Food" },
{ id: "business", text: "Business" },
{ id: "entrepreneur", text: "Entrepreneurs" },
{ id: "history", text: "History" },
{ id: "health", text: "Health" },
{ id: "pet", text: "Pets" },
{ id: "parenthood", text: "Parenthood" },
{ id: "travel", text: "Travel" },
{ id: "india", text: "India" },
{ id: "china", text: "China" },
{ id: "uk", text: "United Kingdom" },
{ id: "us", text: "United States" },
{ id: "world", text: "World" },
{ id: "news", text: "News" },
{ id: "review", text: "Product Review" }
]

使用这些资源,我希望在 javascript 中得到此响应:

[
{ id: "tech", text: "Technology" },
{ id: "review", text: "Product Review" },
{ id: "howto", text: "How To" }
]

到目前为止,我正在这样做👇

categorySorter(categories) {
const categoryState = categorySuggessions.filter(category => category.id === categories.map(category => (category)))
return categoryState
}

这会返回一个空白(即 [] )数组。

你有什么建议?

这里是新手。

最佳答案

您可以使用过滤器包含

let arr = [{ id: "tech", text: "Technology" },{ id: "fin", text: "Finance" },{ id: "digimark", text: "Digital Marketing" },{ id: "coding", text: "Programming" },{ id: "tutorial", text: "Tutorial" },{ id: "howto", text: "How To" },{ id: "writing", text: "Writing" },{ id: "inspire", text: "Inspirational" },{ id: "science", text: "Science" },{ id: "politics", text: "Politics" },{ id: "lifestyle", text: "Lifestyle" },{ id: "food", text: "Food" },{ id: "business", text: "Business" },{ id: "entrepreneur", text: "Entrepreneurs" },{ id: "history", text: "History" },{ id: "health", text: "Health" },{ id: "pet", text: "Pets" },{ id: "parenthood", text: "Parenthood" },{ id: "travel", text: "Travel" },{ id: "india", text: "India" },{ id: "china", text: "China" },{ id: "uk", text: "United Kingdom" },{ id: "us", text: "United States" },{ id: "world", text: "World" },{ id: "news", text: "News" },{ id: "review", text: "Product Review" }]

let ids = ["tech", "review", "howto"]

let op = arr.filter(({id}) => ids.includes(id))

console.log(op)

关于javascript - 如何找到包含这些ID的数组元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55314989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com