How to check if the JSON Object array contains the value defined in an arrary or not?
我有以下JSON数据。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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); |
和后面的数组。
1 | var mainCat = ['Arts, crafts, and collectibles', 'Baby' , 'Antiques'] |
循环JSON数据时,我需要检查对象值是否在数组中列出。如果"是",则做其他事情。
例如
1 2 3 4 5 6 7 | $.each(categoriesJson , function (key, value) { if(value.catName is in array) { //do something here } else { //do something here } }); |
我怎样才能做到这一点?
请尝试以下操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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) } }); |
1 | <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> |
我将筛选初始数据数组以获取匹配类别的数组:
1 | var matchedCategories = categories.filter(i => mainCat.indexOf(i.catName) >= 0); |
然后您可以通过迭代这个子数组来做您需要的事情。