admin管理员组

文章数量:1410737

I'm trying to check if the first arg includes the second on the following array of objects:

whatIsInAName(
[
 { first: "Romeo", last: "Montague" },
 { first: "Mercutio", last: null }, 
 { first: "Tybalt", last: "Capulet" }
], 
{ last: "Capulet" });

I can't use includes() on my logic because it's an array method. I tried to retrieve the objects from the whatIsInAName and pass them into arrays using Object.entries()but that didn't worked too. My two options are to either "transform" the objects into arrays. Or find a different alternative to the includes() method, that i'm able to use in an object.

Any thoughts?

Thank you

I'm trying to check if the first arg includes the second on the following array of objects:

whatIsInAName(
[
 { first: "Romeo", last: "Montague" },
 { first: "Mercutio", last: null }, 
 { first: "Tybalt", last: "Capulet" }
], 
{ last: "Capulet" });

I can't use includes() on my logic because it's an array method. I tried to retrieve the objects from the whatIsInAName and pass them into arrays using Object.entries()but that didn't worked too. My two options are to either "transform" the objects into arrays. Or find a different alternative to the includes() method, that i'm able to use in an object.

Any thoughts?

Thank you

Share asked Dec 17, 2019 at 15:33 Tiago RuivoTiago Ruivo 1832 silver badges11 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

Usesome method to check whether Capulet exists in an array:

let obj = { last: "Capulet" };
const isExist = whatIsInAName.some(f => f.last == obj.last)

const whatIsInAName = [
  { first: "Romeo", last: "Montague" },
  { first: "Mercutio", last: null },
  { first: "Tybalt", last: "Capulet" }
 ];

let obj = { last: "Capulet" };
const isExist = whatIsInAName.some(f => f.last == obj.last)
console.log(`Exists: ${isExist}`)

Or you can use filter to get all objects based on criteria:

const whatIsInAName = [
  { first: "Romeo", last: "Montague" },
  { first: "Mercutio", last: null },
  { first: "Tybalt", last: "Capulet" }
 ];

let obj = { last: "Capulet" };
const result = whatIsInAName.filter(f => f.last == obj.last);

console.log(result)

actually you can do a custom includes using some which will be faster than a map/filter

function whatIsInAName(arr, obj) {
  return arr.some(({
    last
  }) => last === obj.last)
}

const testArray = [{
    first: "Romeo",
    last: "Montague"
  },
  {
    first: "Mercutio",
    last: null
  },
  {
    first: "Tybalt",
    last: "Capulet"
  }
]

const testObj1 = {
  last: "Capulet"
}
const testObj2 = {
  last: "FOO"
}

const res1 = whatIsInAName(testArray, testObj1);
const res2 = whatIsInAName(testArray, testObj2);

console.log(res1);
console.log(res2);

本文标签: javascriptHow do I use includes() or similar in a ObjectStack Overflow