Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript check if each element of an object array is contained in another array

I ave two arrays with objects in them

var requiredfileds=[
    {name:'CVR', value:'cvr_code'},
    {name:'NODE POINT VAL', value:'node_point_val'},

 ]

The second array

var results = [
    {name:'CVB', data:[12,11,233,445]}
    {name:'CVR', data:[125,1,-45,4]}
   ]

Now i want to check to ensure that all the names in the required fields array are in the results array. So from the above two examples i expect it to be false and get the required field missing to be {name:'NODE POINT VAL', value:'node_point_val'},

So i have tried (with es6)

this.is_valid = true;   
this.requiredfields.forEach(field=>{
  this.results.forEach(item=>{
    this.is_valid = item.name === field.name;
  })
})

But the above doesnt work, How do i proceed

like image 598
Geoff Avatar asked Jan 03 '23 06:01

Geoff


1 Answers

Try this: filter the requiredfileds by applying a callback function. This callback function tests if some(any) of the items in results has the same name as the item in requiredfileds.

The result in missing is the filtered array which did not fulfilled the criterion (the one which are present in requiredfileds and not present, by name, in the results array).

If you simply want to know whether there were missing values or not you can just check the missing array length like this: !!missing.length.

var requiredfileds = [{
    name: 'CVR',
    value: 'cvr_code'
  },
  {
    name: 'NODE POINT VAL',
    value: 'node_point_val'
  },

];

var results = [{
  name: 'CVB',
  data: [12, 11, 233, 445]
}, {
  name: 'CVR',
  data: [125, 1, -45, 4]
}];

var missing = requiredfileds.filter(item => !results.some(resultItem => resultItem.name === item.name));

console.log('Any missing: ' + !!missing.length);

console.log(missing);
like image 146
lealceldeiro Avatar answered Jan 05 '23 17:01

lealceldeiro