Lodash在数组中查找数组

时间:2019-02-24 08:14:53

标签: lodash

我有一个看起来像这样的数组:

recipient_Id

我需要查找它是否在数组中并获取该对象。

   var roles = [ 
           { "label": "Super Auditor", "value": 4 }, 
           { "label": "Super Finance Officer", "value": 3 }, 
           { "label": "Super Manager", "value": 2 }, 
           { "label": "Super Admin", "value": 1 } 
   ]

预期结果:

var needToFind = [4, 1]

我只是不知道该怎么做。 TY

2 个答案:

答案 0 :(得分:1)

这是使用VanillaJS的答案

const roles = [ 
           { "label": "Super Auditor", "value": 4 }, 
           { "label": "Super Finance Officer", "value": 3 }, 
           { "label": "Super Manager", "value": 2 }, 
           { "label": "Super Admin", "value": 1 } 
];


const needToFind = [4, 1];

const results = roles.filter(obj => needToFind.includes(obj.value))

console.log(results)

基本上,您将filter应用于roles并使用includes来查看needtoFind中是否存在值

答案 1 :(得分:1)

您可以使用_.intersectionWith()

<div id="popup" style="display: block;">
  <div id="popup-content">
    <iframe allowfullscreen="true" webkitallowfullscreen="true" mozallowfullscreen="true" src="https://www.aparat.com/video/video/embed/videohash/5kInv/vt/frame" width="100%" height="100%"></iframe>   <button type="button" class="close"><strong>×</strong></button>
</div>
</div>
var roles = [ 
  { "label": "Super Auditor", "value": 4 }, 
  { "label": "Super Finance Officer", "value": 3 }, 
  { "label": "Super Manager", "value": 2 }, 
  { "label": "Super Admin", "value": 1 }
]

var needToFind = [4, 1]

var result = _.intersectionWith(roles, needToFind, (a, b) => a.value === b)

console.log(result)