Home>Article>Web Front-end> How to determine whether an array contains objects in es6

How to determine whether an array contains objects in es6

WBOY
WBOY Original
2022-04-25 16:02:01 3237browse

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.

How to determine whether an array contains objects in es6

The operating environment of this tutorial: Windows 10 system, ECMAScript version 6.0, Dell G3 computer.

es6How to determine whether an object is contained in an array

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 Tutorialweb 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn