Reputation: 53
Im trying to search a value from a json in other json and then create a new object from unmatched values.
Here my code:
var anis_report = [ { ani: '525510107835', Times_repeated: 11, Minutes: '33.97' },{ ani: '526642111071', Times_repeated: 9, Minutes: '6.00' },{ani: '524499765316', Times_repeated: 8, Minutes: '31.20' },{ ani: '525517421550', Times_repeated: 7, Minutes: '167.10' }]
var anis_whitelisted_db = [{ ani: '525510107835' },{ ani: '525555742933' },{ ani: '525511049249' },{ ani: '524422242668' }]
Here Im getting the ani value from anis_report to search that value in anis_whitelisted_db but is not working as I espected.
for (ani in anis_whitelisted_db) {
for (ani_2 in anis_report) {
if (anis_report[ani_2]['ani'] !== anis_whitelisted_db[ani]['ani']) {
// Push unmatch object
anis_not_whitelisted.push(anis_report[ani_2])
}
}
}
Thanks in advance
Upvotes: 0
Views: 50
Reputation: 105
You can use for..of to loop through the elements then check for the matching value using the .some method and finally remove the matching element using .splice method:
var anis_report = [ { ani: '525510107835', Times_repeated: 11, Minutes: '33.97' },{ ani: '526642111071', Times_repeated: 9, Minutes: '6.00' },{ani: '524499765316', Times_repeated: 8, Minutes: '31.20' },{ ani: '525517421550', Times_repeated: 7, Minutes: '167.10' }]
var anis_whitelisted_db = [{ ani: '525510107835' },{ ani: '525555742933' },{ ani: '525511049249' },{ ani: '524422242668' }]
var anis_not_whitelisted=anis_report
for (const[i,ani] of anis_report.entries()) {
if(anis_whitelisted_db.some( element => element['ani'] === ani['ani'] )){
anis_not_whitelisted.splice(i,1)
}
}
console.log(anis_not_whitelisted)
Upvotes: 1
Reputation: 1568
You can iterate over an array with for..of
I think there is a logic issue too as you check every item in anis_whitelisted_db and, you must stop to iterate as soon as you have a match for a given ani.
Without any performance optimization (using Set: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set)
const whitelistedAnis = new Set(['ani1', 'ani2', 'ani3']);
for (const ani of anis_report) { // here ani is the { ani: xxx, Times_repeated, ...} object
if (!whitelistedAnis.has(ani.ani)) anis_not_whitelisted.push(ani.ani);
}
This way, you manage only a list of anis and check whether or not a report's ani is in this list.
Upvotes: 1