Home > Software design >  Understanding how to pull info from array
Understanding how to pull info from array

Time:08-14

I have a previously created script that is doing API calls to get various info. Using json fetch. Its used to look up(GET) properties of users, groups, etc.

Here is how it prints. console.log(myArray):

[{user={conversion_id=smitht, ship_id=14.0, ship=Mountain , id=989, name=Smith, Todd, id=8745335.0, system_id=796663, [email protected],, created_at=3055-08-10, //keeps continuing for all users in this account

If I wanted to search the array and return only "name". Is there a better way to accomplish than this? This will print out just the names

for (let i = 0; i < myArray.length; i  ){
  console.log(myArray[i]['user']['name'])

I'm trying to learn what's possible and how to interact. Any other options to search through array? Most examples have sample arrays written out since mine comes from a response its been difficult to follow those examples.

CodePudding user response:

use find https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

function findByLoginId(loginId) {
      const result = myArray.find(user => user.login_id === loginId);
      return result?.name;
}

CodePudding user response:

Check to make sure that the fetched data is valid JSON. You should be able to use JSON.parse on the returned data.

  • Related