gpt4 book ai didi

javascript - 从数组中动态获取对象的值

转载 作者:行者123 更新时间:2023-11-28 11:14:49 26 4
gpt4 key购买 nike

假设我有一个对象 myBook 和一个数组 allCategories

const allCategories = ["sciencefiction", "manga", "school", "art"];

const myBook = {
isItScienceFiction: true,
isItManga: false,
isItForKids: false
}

我想要的:循环遍历类别来检查Book的值,例如,检查我的Book对象中是否存在“sciencefiction”,然后检查它的值

我尝试过的:

1) 使用indexOf

allCategories.map((category) => {
Object.keys(myBook).indexOf(category)
// Always returns -1 because "sciencefiction" doesn't match with "isItScienceFiction"
});

2) 包含包含

allCategories.map((category) => {
Object.keys(myBook).includes(category)
// Always returns false because "sciencefiction" doesn't match with "isItScienceFiction"
});

预期输出:

allCategories.map((category) => {
// Example 1 : Returns "sciencefiction" because "isItScienceFiction: true"
// Example 2 : Returns nothing because "isItManga: false"
// Example 3 : Returns nothing because there is not property in myBook with the word "school"
// Example 4 : Returns nothing because there is not property in myBook with the word "art"


// If category match with myBook categories and the value is true then
return (
<p>{category}</p>
);
});

如果您需要更多信息,请告诉我,我会编辑我的问题。

最佳答案

您可以使用filterfind方法返回新的类别数组,然后使用map方法返回元素数组。

const allCategories = ["sciencefiction", "manga", "school", "art"];
const myBook = {isItScienceFiction: true, isItManga: false, isItForKids: false}

const result = allCategories.filter(cat => {
const key = Object.keys(myBook).find(k => k.slice(4).toLowerCase() === cat);
return myBook[key]
}).map(cat => `<p>${cat}</p>`)

console.log(result)

您还可以使用 reduce 代替 filter 以及 mapendsWith 方法。

const allCategories = ["sciencefiction", "manga", "school", "art"];
const myBook = {isItScienceFiction: true,isItManga: false,isItForKids: false}

const result = allCategories.reduce((r, cat) => {
const key = Object.keys(myBook).find(k => k.toLowerCase().endsWith(cat));
if(myBook[key]) r.push(`<p>${cat}</p>`)
return r;
}, [])

console.log(result)

关于javascript - 从数组中动态获取对象的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55630088/

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