J'ai les données JSON suivantes.
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);
Et tableau suivant.
var mainCat = ['Arts, crafts, and collectibles', 'Baby' , 'Antiques']
Lors de la boucle des données JSON, je dois vérifier si la valeur de l'objet est répertoriée dans un tableau ou non. Si le oui fait autre chose, faites autre chose.
Par exemple
$.each(categoriesJson , function (key, value) {
if(value.catName is in array) {
//do something here
} else {
//do something here
}
});
Comment puis-je atteindre cet objectif?
Essayez ce qui suit:
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>
Je voudrais filtrer le tableau de données initial pour obtenir le tableau des catégories correspondantes:
var matchedCategories = categories.filter(i => mainCat.indexOf(i.catName) >= 0);
Ensuite, vous pouvez faire ce dont vous avez besoin en itérant ce sous-tableau.
J'utilise également l'approche @ dhilt mais avec des inclusions
ex. Si un seul est inclus (retour bool)
categories.filter(i =>
mainCat.includes(i.catName)
).length > 0
? true
: false;