Javascript 如何检查 JSON 对象数组是否包含数组中定义的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47247020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if the JSON Object array contains the value defined in an arrary or not?
提问by Kiran Shahi
I have the following JSON data.
我有以下 JSON 数据。
categories = [
{catValue:1, catName: 'Arts, crafts, and collectibles'},
{catValue:2, catName: 'Baby'},
{catValue:3, catName: 'Beauty and fragrances'},
{catValue:4, catName: 'Books and magazines'},
{catValue:5, catName: 'Business to business'},
{catValue:6, catName: 'Clothing, accessories, and shoes'},
{catValue:7, catName: 'Antiques'},
{catValue:8, catName: 'Art and craft supplies'},
{catValue:9, catName: 'Art dealers and galleries'},
{catValue:10, catName: 'Camera and photographic supplies'},
{catValue:11, catName: 'Digital art'},
{catValue:12, catName: 'Memorabilia'}
];
var categoriesJson = JSON.stringify(categories);
And following array.
和以下数组。
var mainCat = ['Arts, crafts, and collectibles', 'Baby' , 'Antiques']
While looping the JSON data I need to check if the Object value is listed in an array or not. If the yes do something else do another thing.
在循环 JSON 数据时,我需要检查 Object 值是否列在数组中。如果是,做别的事情做另一件事。
For example
例如
$.each(categoriesJson , function (key, value) {
if(value.catName is in array) {
//do something here
} else {
//do something here
}
});
How can I achieve this?
我怎样才能做到这一点?
采纳答案by Mamun
Try the following:
请尝试以下操作:
var categories = [
{catValue:1, catName: 'Arts, crafts, and collectibles'},
{catValue:2, catName: 'Baby'},
{catValue:3, catName: 'Beauty and fragrances'},
{catValue:4, catName: 'Books and magazines'},
{catValue:5, catName: 'Business to business'},
{catValue:6, catName: 'Clothing, accessories, and shoes'},
{catValue:7, catName: 'Antiques'},
{catValue:8, catName: 'Art and craft supplies'},
{catValue:9, catName: 'Art dealers and galleries'},
{catValue:10, catName: 'Camera and photographic supplies'},
{catValue:11, catName: 'Digital art'},
{catValue:12, catName: 'Memorabilia'}
];
var categoriesJson = JSON.stringify(categories);
var mainCat = ['Arts, crafts, and collectibles', 'Baby' , 'Antiques']
$.each(JSON.parse(categoriesJson) , function (key, value) {
if(mainCat.indexOf(value.catName) > -1){
console.log('Exists: ' +value.catName)
}
else{
console.log('Does not exists: ' +value.catName)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
回答by dhilt
回答by Neter
I also use @dhiltapproach but with includes
我也使用@dhilt方法但包含
ex. If even one is included (return bool)
前任。如果甚至包括一个(返回布尔值)
categories.filter(i =>
mainCat.includes(i.catName)
).length > 0
? true
: false;

