0
{
      id: 23323091,
      userId: 1743514,
      teamId: 1693131,
      name: 'test1'
},
{
      id: 2332950,
      userId: 1743514,
      teamId: 1693131,
      name: 'test2'
},
{
      id: 23323850,
      userId: 1743514,
      teamId: 1693131,
      name: 'test3'
}

Im trying find solution how to parse json result returned from GET request in node.js. So I want find in json array with ex. name: 'test3' return id:

Here is full code:

const axios = require('axios');
let token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MTc0MzUxNCwidXNlcm5hbWUiOiJzbmFwa2l0cmljaEBnbWFpbC5jb20iLCJyb2xlIjoiYWRtaW4iLCJ0ZWFtSWQiOjE2OTMxMzEsInRv';
axios.get('https://dolphin-anty-api.com/browser_profiles', {
  headers: {
    Authorization: `Bearer ${token}`
  }

})
  .then(function (response) {
    const data = response.data;
    console.log(data);
  })
  .catch(function (error) {
    console.log(error);
  });

and here is full data response from console log https://pastebin.com/wY0RVsUv

  • What have you tries so far ? It looks to me that a simple `JSON.parse` and a `Array.find` should do the trick. – Seblor Nov 12 '22 at 18:44
  • Does this answer your question? [Find a value in an array of objects in Javascript](https://stackoverflow.com/questions/12462318/find-a-value-in-an-array-of-objects-in-javascript) – derpirscher Nov 12 '22 at 18:46

2 Answers2

1

You can use the Array#find method

const elements = [

  {
    id: 23323091,
    userId: 1743514,
    teamId: 1693131,
    name: 'test1'
  },
  {
    id: 2332950,
    userId: 1743514,
    teamId: 1693131,
    name: 'test2'
  },
  {
    id: 23323850,
    userId: 1743514,
    teamId: 1693131,
    name: 'test3'
  }
]

function search(name) {
  return elements.find(elem => elem.name == name)?.id
}

console.log(search('test3'))
console.log(search('test4'))
LeoDog896
  • 3,472
  • 1
  • 15
  • 40
  • the code is working but when I paste to new .js, but when implement to my code, it push many errors, code is too long to paste it here ;( hmm Ive updated thread fully, if you can look, would be nice – Bella Smith Nov 12 '22 at 19:18
  • That's probably for another question then, but try debugging it -- i notice it's wrapped in data, so try doing `elements.data.find(elem => elem.name == name)?.id` -- no guarantee it would work though. – LeoDog896 Nov 12 '22 at 19:28
  • sadly it doesnt work for return code in data (pastebin link), when I copy array from [ ], it start working, so issue is with return – Bella Smith Nov 12 '22 at 19:34
  • ok figured out this const data = response.data.data; function search(name) { return data.find(elem => elem.name == name)?.id } – Bella Smith Nov 12 '22 at 19:37
0

If you are inside a GET request, to return a Json just do response.json()

Store your JSON inside a const for example

const data = myParsedJsonObject

You can find whatever data you looking for using the ES6 find() method.

const names = data.find(el => el.name === "test3")
Dev
  • 74
  • 3