简体   繁体   English

在对象数组中搜索对象时,是否有返回 true 或 false 的函数?

[英]Is there a function which returns true or false when searching for an object in an array of objects?

I'm looking for a good way to check if an object exist in an array of objects.我正在寻找一种检查对象数组中是否存在对象的好方法 The intended result is true when all keys/values are present in the same object in that array.当所有键/值都存在于该数组的同一对象中时,预期结果为真。

The answers I found by browsing stackoverflow like Find object by id in an array of JavaScript objects which is using jQuery.grep or Find a value in an array of objects in Javascript return the found object.我通过浏览 stackoverflow 找到的答案,例如使用jQuery.grep 的 JavaScript 对象数组中按 id 查找对象在 Javascript 中的对象数组中查找值返回找到的对象。 What I'm looking for is a boolean result (not the found object).我正在寻找的是一个布尔结果(不是找到的对象)。

I know that I can loop for all array elements and then compare each value....etc我知道我可以循环所有数组元素,然后比较每个值......等

But what I mean is if there is a way to use JS methods like this:但我的意思是,如果有一种方法可以使用这样的 JS 方法:

 var listOfObjecs = [ {id: 1, name: "Name 1", score: 11}, {id: 2, name: "Name 2", score: 22}, {id: 3, name: "Name 3", score: 33}, {id: 4, name: "Name 4", score: 44}, {id: 5, name: "Name 5", score: 55}, ]; var isObjectExist = function(search){ return listOfObjecs.filter(function(obj){ if(obj.id===search.id && obj.name===search.name && obj.score===search.score){ return true; } return false; }); } console.log( isObjectExist({id: 3, name: "Name 3", score: 33}) ); //outputs the found object [{id: 3, name: "Name 3", score: 33}] console.log( isObjectExist({id: 9, name: "Name 3", score: 33}) ); //outputs an empty object []

This is because:这是因为:

The filter() method creates a new array with all elements that pass the test implemented by the provided function. filter() 方法创建一个新数组,其中包含通过所提供函数实现的测试的所有元素。

If there is no native JavaScript method (returning true or false) how can update the isObjectExist() function to return true or false?如果没有原生 JavaScript 方法(返回 true 或 false),如何更新isObjectExist()函数以返回 true 或 false?

The Array.prototype.some method: Array.prototype.some方法:

The some() method checks if any of the elements in an array pass a test (provided as a function). some() 方法检查数组中的任何元素是否通过测试(作为函数提供)。 The some() method executes the function once for each element present in the array: If it finds an array element where the function returns a true value, some() returns true (and does not check the remaining values) some() 方法对数组中存在的每个元素执行一次函数:如果找到函数返回真值的数组元素, some() 返回真(并且不检查剩余值)

I'm sharing an example based on comments above, it may help others:我正在根据上面的评论分享一个例子,它可能会帮助其他人:

 const listOfObjecs = [ { id: 1, name: "Name 1", score: 11 }, { id: 3, name: "Name 3", score: 33 }, { id: 2, name: "Name 2", score: 22 }, { id: 3, name: "Name 3", score: 33 }, { id: 4, name: "Name 4", score: 44 }, { id: 5, name: "Name 5", score: 55 }, { id: 3, name: "Name 3", score: 33 }, ]; const search1 = { id: 3, name: "Name 3", score: 33 }; const search2 = { id: 9, name: "Name 3", score: 33 }; // Using Array.prototype.some() const resSomeSearch1 = listOfObjecs.some(item => JSON.stringify(item) === JSON.stringify(search1)); console.log(`resSome(search1): ${resSomeSearch1}`); // outputs: true const resSomeSearch2 = listOfObjecs.some(item => JSON.stringify(item) === JSON.stringify(search2)); console.log(`resSome(search2): ${resSomeSearch2}`); // outputs: false // Using Array.prototype.filter() const resFilterSearch1 = !!listOfObjecs.filter(item => JSON.stringify(item) === JSON.stringify(search1)).length; console.log(`resFilter(search1): ${resFilterSearch1}`); // outputs: true const resFilterSearch2 = !!listOfObjecs.filter(item => JSON.stringify(item) === JSON.stringify(search2)).length; console.log(`resFilter(search2): ${resFilterSearch2}`); // outputs: false // Using Array.prototype.find() const resFindSearch1 = !!listOfObjecs.find(item => JSON.stringify(item) === JSON.stringify(search1)); console.log(`resFind(search1): ${resFindSearch1}`); // outputs: true const resFindSearch2 = !!listOfObjecs.find(item => JSON.stringify(item) === JSON.stringify(search2)); console.log(`resFind(search2): ${resFindSearch2}`); // outputs: false

This works for me:这对我有用:

const findInArray = (myArray, item) => {
 !!myArray.find((el) => el == item)
};

Update, even easier:更新,更简单:

 ['cat', 'dog', 'bat'].includes('dog');  

The find() method returns a value of the first element in the array that satisfies the provided testing function. find() 方法返回数组中满足提供的测试函数的第一个元素的值。 Otherwise undefined is returned.否则返回 undefined。 So no boolean result.所以没有布尔结果。

@AlaDejbali's comment on his post. @AlaDejbali 对他的帖子的评论。

Let's take this array :让我们以这个数组为例:

var arr = [{
        name: "Ala",
        age: 20,
    },
    {
        name: "Jhon",
        age: 22,
    },
    {
        name: "Melissa",
        age: 12,
    },
];

Of course, find() returns the whole object inside your array but that depends on your implemented function inside find for example :当然, find()返回数组中的整个对象,但这取决于您在 find 中实现的函数,例如:

function findObject(arr, value) {
    if (Array.isArray(arr)) {
        return arr.find((value) => {
            return value.age === 20;
        });
    }
}

When we call this function like this :当我们像这样调用这个函数时:

console.log(findObject(arr, 20));

The resul will be :结果将是:

{name: "Ala", age: 20}

And as far as we know undefined is not an object so we can test the returned result :据我们所知undefined不是一个object所以我们可以测试返回的结果:

function findObject(arr, value) {
    const element = arr.find((value) => {
        return value.age === 20;
    });
    return typeof element === "object" ? true : false;
}

Or in other way :或以其他方式:

function findObject(arr, value) {
        const element = arr.find((value) => {
            return value.age === 20;
        });
        return typeof element === "undefined" ? false : true;
    }

return boolean value if an object exists in array of objects.如果对象存在于对象数组中,则返回布尔值。

 var listOfObjecs = [ { id: 1, name: "Name 1", score: 11 }, { id: 2, name: "Name 2", score: 22 }, { id: 3, name: "Name 3", score: 33 }, { id: 4, name: "Name 4", score: 44 }, { id: 5, name: "Name 5", score: 55 }, ]; var object = { id: 3, name: "Name 3", score: 33 }; var booleanValue = listOfObjecs.filter((item) => item.id === object.id && item.name === object.name && item.score === object.score).length > 0 console.log({booleanValue})

尝试这个:

!!arr.find(function(){...})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在数组中搜索单个字符时返回true或false - Returning true or false when searching for individual characters in an array 是否有任何更高阶的 function 可以遍历对象数组并返回 true 或 false - Is there any Higher order function which can iterate through a array of objects and return true or false 数组推送返回 true 或 false 而不是推送的对象 - array push returns true or false instead of the objects pushed vuex 函数 - 根据对象值返回 true 或 false - vuex function - returns true or false based on object value Keycloak 对象属性“已验证”在应该为真时返回假 - Keycloak object property "authenticated" returns false when should be true 如果if语句中的JavaScript函数为true,则它返回false。 - Javascript function returns false when it should be true from an if statement? 当Javascript函数返回false时返回true - Javascript function returns true when it should return false 当函数在Javascript中将布尔值设置为true时,布尔值将返回false - Bool value returns false when the function set it to true in Javascript 如何在 javascript 中编写一个 function ,它在调用时返回 true 或 false 作为交替而不使用闭包保留全局变量? - How to write a function in javascript which returns true or false as alternating when its invoked without keeping global variables using closure? JavaScript检查对象数组在应为true时将为false - JavaScript checking an array of objects is coming up false when it should be true
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM