Home >Web Front-end >Front-end Q&A >How to determine whether an array contains objects in es6
Method: 1. Use "array object.find(object condition)". This method returns the value of the first element in the array that satisfies the provided function. If it does not exist, it returns undefined; 2. Use "array object.find(object condition)". findIndex(object condition)", this method returns the index of the first element in the array that satisfies the provided function. If it does not exist, it returns -1.
The operating environment of this tutorial: Windows 10 system, ECMAScript version 6.0, Dell G3 computer.
es6Determine if an object already exists in the array.
The find() method returns the value of the first element in the array that satisfies the provided test function. Otherwise, undefined is returned.
The findIndex() method returns the index of the first element in the array that satisfies the provided test function. Otherwise, -1 is returned.
The example is as follows:
find method:
var objArr = [{id:1, name:'jiankian'}, {id:23, name:'anan'}, {id:188, name:'superme'}, {id:233, name:'jobs'}, {id:288, name:'bill', age:89}, {id:333}] ; var ret2 = objArr.find((v) => { return v.id == 233; }); console.log(ret2); // return {id:233, name:'jobs'}
// When undefined is returned, it means there is no objArr, you can add
findIndex method:
var objArr = [{id:1, name:'jiankian'}, {id:23, name:'anan'}, {id:188, name:'superme'}, {id:233, name:'jobs'}, {id:288, name:'bill', age:89}, {id:333}] ; var ret2 = objArr.findIndex((v) => { return v.id == 233; }); console.log(ret2); // return 3
// When -1 is returned, it means that there is no objArr and can be added
[Related recommendations: javascript video Tutorial、web front-end】
The above is the detailed content of How to determine whether an array contains objects in es6. For more information, please follow other related articles on the PHP Chinese website!