简体   繁体   中英

Finding an object in JSON with find()

it might seem a stupid question.... but...

so im just trying to find an object which is stored in an array (JSON) and when i execute this simple code it gives me undefined

let test = [
    {id : "1", name:"ExpressJS", phone : "123"},
    {id : "2", name:"ReactJS", phone:"456"},
    {id : "3", name:"CRUD programming", phone:"789"},
]
let data = test.find((a) => {a.id == 1})
console.log(data);

**result: undefined **

You are not returning anything from the arrow function:

(a) => {a.id == 1}

You could fix it with one of these two options:

let data = test.find((a) => a.id == 1);

or:

let data = test.find((a) => { return a.id == 1 });

When you use curly braces in an arrow function, you need an explicit return statement. Or just omit the curly braces

let test = [
    {id : "1", name:"ExpressJS", phone : "123"},
    {id : "2", name:"ReactJS", phone:"456"},
    {id : "3", name:"CRUD programming", phone:"789"},
]
let data = test.find((a) => a.id === "1")
console.log(data);

If you want to use curly braces, you have to put a return keyword. Otherwise, you don't need to use the return keyword explicitly. See the documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

See both ways in the following code.

let test = [
    {id : "1", name:"ExpressJS", phone : "123"},
    {id : "2", name:"ReactJS", phone:"456"},
    {id : "3", name:"CRUD programming", phone:"789"},
]

let res1 = test.find((a) => a.id == 1)

let res2 = test.find((a) => { return a.id == 1 })

console.log(res1); // { id: '1', name: 'ExpressJS', phone: '123' }
console.log(res2); // { id: '1', name: 'ExpressJS', phone: '123' }

In both ways, we will get the same result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM