Skip to content
Advertisement

Ajax how to find something in array of objects via find method

In backend PHP I have this defined in loop:

 foreach ( $data as $res ){
$approved[ ]        = [ 'id' => $count, 'title' => "some title" ];
$count++;$title=...
)

and then final list is created:

$list[ ] = [ 'list' => 'approved', 'values' => $approved ];
return ['list' => $list ];

In javascript I am getting these results via ajax call:

this.myoutput = {};
    this.http.get('backend_url).then(data => {
      let result = this.helper.isJson( data.response ) || [ ];
      console.log(result);

      this.myoutput.approved   = result.list.find( item => item.list === 'approved' );

      console.log(this.myoutput.approved);

    })

The first console.log(result); gives me all data something like:

list: (1) […]

0: {…}
​​​
list: "approved"
​​​
values: (13) […]
​​​​
0: Object { id: "1", title: "aaa" }
​​​​
1: Object { id: "2", title: "bbb" }
​​​​
2: Object { id: "3", title: "ccc" }
​​​

but console.log(this.myoutput.approved); gives me undefined. Is something what I am doing wrong here?

Advertisement

Answer

The key that holds your array values is named values, not list. So this should work:

this.myoutput = {};
    this.http.get('backend_url).then(data => {
      let result = this.helper.isJson( data.response ) || [ ];
      console.log(result);

      this.myoutput.approved   = result.values.find( item => item.list === 'approved' );

      console.log(this.myoutput.approved);

    })

But what are you trying to find? If you check the values array, it contains id and title, not list? so to find one item in your array, something like:

this.myoutput.approved   = result.values.find( item => item.id === "3" );

would make more sense to me. Note that if nothing is found, the find() method will indeed return undefined as per the specification: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

Good luck!

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement