Gocha Gochitashvili
Gocha Gochitashvili

Reputation: 305

Access array values - AngularJs

Hello I have array of friends this.venner

enter image description here

also I have array called this.convensations and output is like this.venner, but id here is called partner_id (partner_id output is 54312, 54345, 54346 )

now I want compare if this.convensation partner_id and this.venner id if is same

something like this:

if (this.convensation in this.venner) {
  //do something
} else {
  // do something
}

Upvotes: 0

Views: 38

Answers (3)

Matthew Cawley
Matthew Cawley

Reputation: 2818

You can use the Array.prototype.some() method.

If you wrap that in it's own checkExistsInArray function...

function checkExistsInArray(arr, compareObj){
  return arr.some(function(obj){ 
    return compareObj[Object.keys(compareObj)] === obj[Object.keys(compareObj)];
  });
}

... then you should be able to use that for both arrays by passing in a custom compare object.

var friendExists = checkExistsInArray(this.venner, { id: this.friend });

var conversationExists = checkExistsInArray(this.conversations, { partner_id: this.friend });

Side Note : As others have pointed out, there are libraries out there to readily do this sort of thing. Two of the main players I'm aware of are Underscore.js and Lodash. Even if you choose not to use them, it can sometimes be helpful to see how they work under the hood when looking for a little bit of inspiration.

Upvotes: 1

Dushyantha
Dushyantha

Reputation: 217

Simply you can solve this using Undescore.js _.find function

if (.find(this.friend, {"id":this.venner) {
  //do something
} else {
  // do something
}

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222552

You can use filter,

var result = this.venner.filter(t=>t.id === '54312');
if (result.length >0) {
  //do something
} else {
  // do something
}

Upvotes: 1

Related Questions