0

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?

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.