简体   繁体   English

使用 find() 在 JSON 中查找 object

[英]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所以我只是想找到一个存储在数组(JSON)中的 object,当我执行这个简单的代码时,它给了我未定义的

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:您没有从箭头 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.当您在箭头 function 中使用花括号时,您需要一个显式的 return 语句。 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.如果要使用花括号,则必须输入return关键字。 Otherwise, you don't need to use the return keyword explicitly.否则,您不需要显式使用return关键字。 See the documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions请参阅文档: 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.在这两种方式中,我们都会得到相同的结果。

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

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