Search code examples
javascriptarraysjsongetxmlhttprequest

How to get content from JSON.parse(xhr.response)


I send a GET request to the client and objects in the body are returned to me. Now I need to work with one specific object, for example, display the name of the object under ID 3. How can I do this?

const requestURL = '/coffee/all'

const xhr = new XMLHttpRequest();

xhr.open('GET', requestURL)

xhr.onload = () => {

    var datas = JSON.parse(xhr.response);

    console.log(datas)
}

xhr.send()

enter image description here


Solution

  • const requestURL = '/coffee/all'
    const xhr = new XMLHttpRequest();
    
    xhr.open('GET', requestURL)
    
    xhr.onload = () => {
    
        var datas = JSON.parse(xhr.response);
    
        console.log(datas.find(item => item.id === 3).name)
    }
    
    xhr.send()