验证数组内属性对象的值

时间:2018-12-18 20:19:58

标签: javascript angularjs lodash

我有以下数组:

arrayObject = [
    { type: "one" },
    { type: "two" },
    { type: "other" },
];

我还有以下带有值的数组:

types = [
    "one",
    "other"
];

我需要验证这两个值是否存在,如果不存在,则必须阻止它们在流程中前进,目前我正在做的是:

arrayObject.filter(object => types.includes(object.type))

此代码在不存在时返回我,但在一个或另一个存在时也返回我,但是我需要知道这两个是否存在,这对我不起作用

3 个答案:

答案 0 :(得分:3)

使用every

if (types.every(t => arrayObject.findIndex(a => a.type === t) > -1))

答案 1 :(得分:1)

您还可以将Array.fromArray.everyArray.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)

使用typearrayObject拔下_.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>