Home>

For the associative array as shown below, extract each object with id: 1 and
I created the code because I wanted to put it in a variable called result.

const test = [
  {id: 1, name: "John"},
  {id: 2, name: "Bob"},
  {id: 3, name: "Bobby"},
]
const test = [
  {id: 1, name: "John"},
  {id: 2, name: "Bob"},
  {id: 3, name: "Bobby"},
]
const result = test.filter ((item) =>{return item.id = 1})
console.log (result)

When I ran the above code, the result was output with the value of test as it was.

code


{id: 1, name: "John"}

How can I output in the form of?
I would appreciate it if you could teach me.

  • Answer # 1

    = =Is missing one.
    In substitution,1ToidI assigned it to a property
    Logically,Always trueTherefore, it always returns an array of all elements.

    Therefore, perform the comparison operation as shown below.

    const result = test.filter ((item) =>{return item.id == 1});

    Also, if you want to get one target object instead of an array, it is as follows.
    (Valid as long as you know that there is only one target object)

    const result = test.filter (item =>item.id == 1) [0];

    Also, under the above conditions (it is known that there is only one target object),filterthan,
    find findThe method can be obtained in one shot, so I wonder if that is better.

    const result = test.find (item =>item.id == 1);