我有以下数组:
arrayObject = [
{ type: "one" },
{ type: "two" },
{ type: "other" },
];
我还有以下带有值的数组:
types = [
"one",
"other"
];
我需要验证这两个值是否存在,如果不存在,则必须阻止它们在流程中前进,目前我正在做的是:
arrayObject.filter(object => types.includes(object.type))
此代码在不存在时返回我,但在一个或另一个存在时也返回我,但是我需要知道这两个是否存在,这对我不起作用
答案 0 :(得分:3)
使用every
if (types.every(t => arrayObject.findIndex(a => a.type === t) > -1))
答案 1 :(得分:1)
您还可以将Array.from
与Array.every
和Array.includes
结合使用:
const arrayObject = [{ type: "one" }, { type: "two" }, { type: "other" }];
const types = ["one", "other"];
const result = types.every(t => Array.from(arrayObject, x=> x.type).includes(t))
console.log(result)
您也可以使用Array.some
获得更简洁的解决方案:
const arrayObject = [{ type: "one" }, { type: "two" }, { type: "other" }];
const types = ["one", "other"];
const result = types.every(t => arrayObject.some(x => x.type === t))
console.log(result)
并且由于您具有lodash
标签:
const arrayObject = [{ type: "one" }, { type: "two" }, { type: "other" }];
const types = ["one", "other"];
const result = _.every(types, x => _.some(arrayObject, {type: x}))
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
答案 2 :(得分:0)
使用type
从arrayObject
拔下_.map()
。使用_.intersection()
,并将结果长度与types
数组的长度进行比较:
const arrayObject = [{"type":"one"},{"type":"two"},{"type":"other"}];
const types = ["one","other"];
const result = _.eq(
_.intersection(types, _.map(arrayObject, 'type')).length
, types.length);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>