【问题标题】:How to get content from JSON.parse(xhr.response)如何从 JSON.parse(xhr.response) 获取内容
【发布时间】:2021-01-03 05:22:18
【问题描述】:

我向客户端发送了一个 GET 请求,并且正文中的对象返回给我。现在我需要处理一个特定的对象,例如,在 ID 3 下显示对象的名称。我该怎么做?

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()

【问题讨论】:

  • 没有 ID 为 3 的对象...但如果有的话,您可以使用 let object = datas.content.find(({id}) => id === 3)
  • 您可能是指索引 3 而不是项目 3?如果是这样,您可以通过 datas.content[3] 访问它

标签: javascript arrays json get xmlhttprequest


【解决方案1】:
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()

【讨论】:

  • 嗨,欢迎来到 Stack Overflow!如果您在代码中提供解释,则答案更容易理解
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-21
  • 2016-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多