代码之家  ›  专栏  ›  技术社区  ›  sioesi

验证数组内属性对象的值

  •  0
  • sioesi  · 技术社区  · 6 年前

    我有以下数组:

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

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

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

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

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

    这段代码在不存在的时候返回我,在一个或另一个存在的时候返回我,但是我需要知道这两个是否存在,它对我不起作用。

    3 回复  |  直到 6 年前
        1
  •  3
  •   tymeJV    6 年前

    使用 every

    if (types.every(t => arrayObject.findIndex(a => a.type === t) > -1))
    
        2
  •  1
  •   Akrion    6 年前

    你也可以用 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>
        3
  •  0
  •   Ori Drori    6 年前

    摘下 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>