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 badges2 Answers
Reset to default 7Usesome
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
版权声明:本文标题:javascript - How do I use .includes() or similar in a Object? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744935304a2633145.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论