如何检查JSON对象数组是否包含数组中定义的值? [英] How to check if the JSON Object array contains the value defined in an arrary or not?
本文介绍了如何检查JSON对象数组是否包含数组中定义的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下JSON数据.
I have the following JSON data.
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']
在循环JSON数据时,我需要检查Object值是否在数组中列出.如果是,则做其他事情.
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.
例如
$.each(categoriesJson , function (key, value) {
if(value.catName is in array) {
//do something here
} else {
//do something here
}
});
我该如何实现?
推荐答案
尝试以下操作:
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>
这篇关于如何检查JSON对象数组是否包含数组中定义的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文