【问题标题】:Check if object in array contain all value in another object in array检查数组中的对象是否包含数组中另一个对象中的所有值
【发布时间】:2020-07-30 10:16:40
【问题描述】:

我花了几个小时比较数组中的两个对象,但我没有找到实现它的方法

假设我有这些名为 compareWith 的数组:

[{a:1},{b:2},{c:3}]

这是一个要比较的数组和预期的结果:

  1. [{b:2}] true -> 因为 {b:2} 在 compareWith
  2. [{c:3},{a:1}] true -> 因为 {c:3} 和 {a:1} 在 compareWith
  3. [{a:1},{b:2}] true -> 因为 {a:1} 和 {b:2} 在 compareWith
  4. [{a:1},{d:3}] false -> 因为 {d:3} 不在 compareWith 中,甚至 {a:1} 在 compareWith

如何使用 javascript 函数/lodash 实现上述结果?

编辑:

刚刚尝试过,但结果我想要一个boolean

import _ from 'lodash';

var a = [{a:1},{b:2},{c:3}]
var b = [{c:3},{a:1}]

let result = _.differenceWith(a, b, _.isEqual)
console.log(JSON.stringify(result)) //[{b:2}]

【问题讨论】:

  • 你能把你拥有的东西发给我们,即使它不起作用
  • 告诉我们你到目前为止尝试了什么?
  • 我已经尝试了很多方法使用包含,一些,查找,lodash 函数的差异,因为我没有得到结果,我只是删除了我迄今为止尝试过的@AlwaysHelping跨度>
  • 我们需要看看您为实现这一目标所做的努力吗?请记住,stackoverflow 不是编码服务。
  • @AlwaysHelping 当然,我知道 SO 不是编码服务,这就是为什么我使用一个简单的数组案例而不是在我的帖子中显示我的整个问题

标签: javascript lodash


【解决方案1】:

你可以使用filtervanilla javascript

main = [{a:1},{b:2},{c:3}]
a1=[{b:2}]
a3=[{c:3},{a:1}]
a4=[{a:1},{b:2}] 
a5=[{a:1},{d:3}] 

function check(main,a){
  res =main.filter(o=>a.some(e=>Object.keys(e)[0]==Object.keys(o)[0] && Object.values(e)[0]==Object.values(o)[0]))
  return res.length==a.length ? true : false
}
  console.log(check(main,a1))
  console.log(check(main,a3))
  console.log(check(main,a4))
 console.log(check(main,a5))

【讨论】:

    【解决方案2】:

    你可以这样做

    function compareWith(originalArray, arrayToCompareWith){
    
       for(let obj of originalArray)
          if(!arrayToCompareWith.find((x)=>_.isEqual(x, obj)))
             return false;
       return true;
    
    }
    

    或者只在一行中使用 lodash,如下所示

    var main = [{a:1},{b:2},{c:3}],
    a1=[{b:2}],
    a2=[{c:3},{a:1}],
    a3=[{a:1},{b:2}], 
    a4=[{a:1},{d:3}];
    
    function compareWith(originalArray, arrayToCompareWith){
    
       return _.differenceWith(arrayToCompareWith, originalArray, _.isEqual).length == 0;
    }
    
    console.log(compareWith(main, a1));
    console.log(compareWith(main, a2));
    console.log(compareWith(main, a3));
    console.log(compareWith(main, a4));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.19/lodash.min.js"></script>

    【讨论】:

    • 我认为我的问题可以用一个班轮代码来解决,比如let isSame = _.difference(arrayToCompare, compareWith).length === 0
    • 你试过_.differenceWith(compareWith, arrayToCompare, _.isEqual).length == 0;
    猜你喜欢
    • 1970-01-01
    • 2016-04-24
    • 2019-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    • 2019-07-26
    相关资源
    最近更新 更多