Javascript 从数组中动态获取对象的值
假设我有一个对象Javascript 从数组中动态获取对象的值,javascript,arrays,object,Javascript,Arrays,Object,假设我有一个对象myBook和一个数组allCategories const allCategories = ["sciencefiction", "manga", "school", "art"]; const myBook = { isItScienceFiction: true, isItManga: false, isItForKids: false } 我想要什么:在类别上循环以检查图书的价值,例如,检查我的图书对象中是否存在“科幻小说”,然后检查其价值 我尝试过
myBook
和一个数组allCategories
const allCategories = ["sciencefiction", "manga", "school", "art"];
const myBook = {
isItScienceFiction: true,
isItManga: false,
isItForKids: false
}
我想要什么:在类别上循环以检查图书的价值,例如,检查我的图书对象中是否存在“科幻小说”
,然后检查其价值
我尝试过的:
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>
);
});
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>
);
});
allCategories.map((categority)=>{
//示例1:返回“Science虚构”,因为“IsitScienceEffect:true”
//示例2:返回nothing,因为“isItManga:false”
//示例3:不返回任何内容,因为myBook中没有带单词“school”的属性
//示例4:不返回任何内容,因为myBook中没有包含单词“art”的属性
//如果类别与myBook类别匹配且值为true,则
返回(
{类别}
);
});
如果您需要更多信息,请告诉我,我会编辑我的问题。您可以使用filter
和find
方法返回新的类别数组,然后使用map
方法返回元素数组
const allCategories=[“科幻小说”、“漫画”、“学校”、“艺术”];
const myBook={IsitScienceEffect:true,isItManga:false,IsitForkId:false}
const result=allCategories.filter(cat=>{
const key=Object.keys(myBook).find(k=>k.slice(4).toLowerCase()==cat);
归还我的书[钥匙]
}).map(cat=>`${cat}`)
console.log(结果)
您可以使用
Object.keys(myBook).forEach(function(key){console.log(myBook[key])})
。。。将您的代码放置在console.log中,而不是。这可以在没有硬编码的情况下实现,也是最佳实践 您真的不应该保留许多包含布尔值的属性。虽然这可能适用于1、2或3个类别,但对于几百个类别来说,效果并不理想。相反,只需将类别存储在数组中:
const myBook = {
categories: ["sciencefiction", "manga", "kids"],
};
如果您已经获得了一些具有旧结构的对象,则可以轻松地转换它们:
const format = old => {
const categories = [];
if(old.isItScienceFiction)
categories.push("sciencefiction");
if(old.isItManga)
categories.push("manga");
if(old.isItForKids)
categories.push("kids");
return { categories };
};
现在检查一本书是否包含某一类别:
const isManga = myBook.categories.includes("manga");
现在,渲染也非常简单:
myBook.categories.map(it => <p>{it}</p>)
myBook.categories.map(it=>{it})
您可以为对象的类别和键创建一个:
const allCategories=[“科幻小说”、“漫画”、“学校”、“艺术”],
myBook={IsitScienceEffect:true、isItManga:false、IsitForkId:false}
const map=Object.keys(myBook)
.reduce((r,k)=>r.set(k.slice(4.toLowerCase(),k),新映射);
/*地图:
{“科幻小说”=>“科学效应”}
{“漫画”=>“isItManga”}
{“forkids”=>“isItForKids”}
*/
allCategories.forEach(键=>{
让keyInObject=map.get(key);//对象中的键名
让value=myBook[keyInObject];//对象中键的值
日志(键、keyInObject、值)
if(keyInObject&&value){
//如果具有当前键且值为true,请执行某些操作
}
})
使用带有RegExp的Array.filter()
和Array.find()
查找具有匹配键的类别。使用Array.map()
将类别转换为字符串/JSX/etc
const findMatchingCategories=(对象,类别)=>{
常量键=对象键(obj);
返回所有类别
.filter(类别=>{
常量模式=新的RegExp(类别“i”);
返回obj[keys.find(c=>pattern.test(c));
})
.map(category=>`${category}`);
};
const allCategories=[“科幻小说”、“漫画”、“学校”、“艺术”];
const myBook={
IsitScienceEffect:没错,
伊斯特曼加:错,
isItForKids:false
};
const result=findMatchingCategories(myBook,allCategories);
控制台日志(结果)代码>您可以这样尝试:
const allCategories=[“科幻小说”、“漫画”、“学校”、“艺术”];
const myBook={
IsitScienceEffect:没错,
伊斯特曼加:错,
isItForKids:false
};
const myBookKeys=Object.keys(myBook);
const result=allCategories.map(category=>{
const foundIndex=myBookKeys.findIndex(y=>y.toLowerCase().includes(category.toLowerCase());
如果(foundIndex>-1&&myBook[myBookKeys[foundIndex]])
返回`${category}`;
});
控制台日志(结果)
您可以在myBook
对象中修改关键字名称,以便于查找,如:
const allCategories = ["sciencefiction", "manga", "school", "art"];
const myBook = {
isItScienceFiction: true,
isItManga: false,
isItForKids: false
}
const modBook = {}
Object.keys(myBook).map((key) => {
const modKey = key.slice(4).toLowerCase()
modBook[modKey] = myBook[key]
})
const haveCategories = allCategories.map((category) => {
if (modBook[category]) {
return <p>{category}</p>
}
return null
})
console.log(haveCategories)
const allCategories=[“科幻小说”、“漫画”、“学校”、“艺术”];
const myBook={
IsitScienceEffect:没错,
伊斯特曼加:错,
isItForKids:false
}
常量modBook={}
Object.keys(myBook.map)((key)=>{
const modKey=key.slice(4).toLowerCase()
modBook[modKey]=myBook[key]
})
const haveCategories=allCategories.map((category)=>{
if(modBook[类别]){
返回{category}
}
返回空
})
console.log(haveCategories)
不可能将科幻小说
转换为IsitScienceEffect
,并且对每个类别
循环使用myBook
的所有键也不是最佳选择
但是将isItScienceFiction
转换为sciencefiction
非常简单,因此您可以从myBook
创建newMyBook
,并使用它来检查
创建newMyBook
是一次性的开销
const allCategories=[“科幻小说”、“漫画”、“学校”、“艺术”];
const myBook={IsitScienceEffect:true,isItManga:false,IsitForkId:false};
const newMyBook=Object.keys(myBook.reduce)(a,k)=>{
返回{…a[k.replace('isIt','').toLowerCase()]:myBook[k]};
}, {});
console.log(
allCategories.filter(category=>!!newMyBook[category]).map(category=>`${category}`)
);代码>嗯。。。你可以在所有的书键上循环,去掉“isIt”,然后把它小写。。。?不确定你到底在问什么,因为你似乎已经知道你的方法失败的确切原因。这样的输入很难看。我的意思是,不能保证小写字母总能解决这个问题。还有其他关系吗