Michael Coder Michael Coder - 8 months ago 71
JSON Question

Use Lodash to find the indexOf a JSON array inside of an [] array

I have an array that looks something like this.

Users : {
0 : { BidderBadge: "somestuff", Bidders: 6, }
1 : { BidderBadge: "somemorestuff", Bidders: 7,}

I want to search the array using lodash to find a value inside of each of the user objects.

Specifically, I want to use values from another similar array of objects to find the value.

var bidArray = [];
_.each(this.vue.AllUsers, function(user) {
_.each(this.vue.Bids, function(bid) {
if(user.BidderBadge == bid.Badge) {

This is what I have and it works, but I want to do it using only one loop instead of two. I want to use something like _.indexOf. Is that possible?


It is difficult to give an accurate answer with an example that doesn't coincide with the input that your provide.

Anyway, supposing your data structures were more or less like this ones, you could solve the problem with lodash _.intersectionWith.

Intersect both arrays using a comparator that checks the correct object properties. Also, take into account that users must go first in the intersection due to the fact that you're interested in its values.

function comparator(user, bid) {
  return user.BidderBadge === bid.Badge;
console.log(_.intersectionWith(users, bids, comparator));

Here's the fiddle.