如何检查JSON对象数组是否包含在数组中定义的值?

7

我有以下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);

接下来是数组。

var mainCat = ['Arts, crafts, and collectibles', 'Baby' , 'Antiques']

在循环JSON数据时,我需要检查对象值是否列在数组中。如果是,则执行某些操作,否则执行其他操作。

例如:

$.each(categoriesJson , function (key, value) {
    if(value.catName is in array) {
        //do something here 
    } else {
        //do something here
    }
});

我该如何实现这个目标?

1
array.indexOf(value.catName) !== -1 // 在数组中 - JohanP
可能是重复的问题,参见如何在JavaScript中检查字符串数组是否包含一个字符串? - Nisarg Shah
另请参见:https://dev59.com/E3VC5IYBdhLWcg3wnCj6 - Nisarg Shah
3个回答

6
请尝试以下操作:

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>


3

我会使用过滤器来获取匹配类别的数组:

var matchedCategories = categories.filter(i => mainCat.indexOf(i.catName) >= 0);

那么,您可以通过迭代这个子数组来完成所需的操作。

0

我也使用@dhilt的方法,但是加入了includes

例如,如果有一个被包含(返回bool)

  categories.filter(i =>
    mainCat.includes(i.catName)
  ).length > 0
    ? true
    : false;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接