【问题标题】:Verify value of property object inside Array验证 Array 中属性对象的值
【发布时间】:2018-12-18 20:19:58
【问题描述】:

我有以下数组:

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

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

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

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

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

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

【问题讨论】:

    标签: javascript angularjs lodash


    【解决方案1】:

    使用every

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

    【讨论】:

    • 好极了,它成功了!!,只要通过正确的时间框架!
    【解决方案2】:

    您还可以将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>

    【讨论】:

      【解决方案3】:

      使用_.map()arrayObject 中提取type。使用_.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>

      【讨论】:

        猜你喜欢
        • 2010-11-11
        • 1970-01-01
        • 2019-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-01
        相关资源
        最近更新 更多