【问题标题】:How to check if the JSON Object array contains the value defined in an arrary or not?如何检查 JSON 对象数组是否包含数组中定义的值?
【发布时间】:2018-04-25 02:43:30
【问题描述】:

我有以下 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 数据时,我需要检查 Object 值是否列在数组中。如果是,则做其他事情。

例如

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

我怎样才能做到这一点?

【问题讨论】:

标签: javascript jquery arrays json


【解决方案1】:

尝试以下方法:

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>

【讨论】:

    【解决方案2】:

    我会filter初始数据数组得到匹配类别的数组:

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

    然后你可以通过迭代这个子数组来做你需要的事情。

    【讨论】:

      【解决方案3】:

      我也使用 @dhilt 方法,但包含

      例如。如果甚至包含一个(返回布尔值)

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-24
        • 2019-07-26
        • 2020-06-07
        • 1970-01-01
        • 2022-08-18
        • 1970-01-01
        • 2020-08-09
        • 1970-01-01
        相关资源
        最近更新 更多