Javascript检查对象数组的每个元素是否包含在另一个数组中 [英] 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'},
]
第二个数组
var results = [
{name:'CVB', data:[12,11,233,445]}
{name:'CVR', data:[125,1,-45,4]}
]
现在,我要检查以确保所需字段数组中的所有名称都在结果数组中.因此,从上面的两个示例中,我希望它为假,并使必填字段丢失为{name:'NODE POINT VAL', value:'node_point_val'},
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'},
所以我已经尝试过(使用es6)
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
推荐答案
尝试以下操作: some
results
中的a>(任意)项与requiredfileds
中的item
具有相同的名称.
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
.
missing
中的结果是不满足条件的过滤数组(存在于requiredfileds
中但名称不存在于results
数组中的那个数组).
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).
如果只想知道是否缺少值,则可以检查missing
数组长度,如下所示:!!missing.length
.
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);
这篇关于Javascript检查对象数组的每个元素是否包含在另一个数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!