【问题标题】:How do i use a field of a json ojected to find another field of a different json object? (Javascript) [closed]如何使用 json 对象的字段来查找不同 json 对象的另一个字段? (Javascript) [关闭]
【发布时间】:2022-01-04 09:39:54
【问题描述】:

基本上我有一个 Get 请求,它返回一个包含多个 json 对象的响应。我需要根据他的名字获取一个特定的 json 对象,操作该名称并根据该修改后的名称(在 javascript 中)找到另一个对象的 id。
示例:

  • 我有一个名称为“XXXX Published”、ID:“1”的 json。
  • 我需要获取名称,将其更改为“XXXX Restricted”,然后找到具有该名称的对象的 ID。

任何人都可以给我一个代码 sn-p 从中工作吗?

【问题讨论】:

  • 你得到数组中的对象吗?你能展示一个示例回复吗?

标签: javascript json


【解决方案1】:

我已假定此响应中的响应格式,如果不正确,请告诉我。

    const response = [
        {id: 1, name: "XXXX Published"}, 
        {id: 2, name: "XXXX Restricted"}, 
        {id: 3, name: "h3"}
    ]

    function replaceName(findName, name) {
        const index = response.findIndex(i => i.name === findName)
        if(index !== -1) {
            response[index].name = name;
        }
    }

    const oldName = "XXXX Published";
    const newName = 'XXXX Restricted'

    // This is the id that already has the new name
    const originalId = response.find(i => i.name === newName)?.id;

    // This mutates the response and changes the name
    replaceName(oldName, newName)

【讨论】:

  • 非常感谢:)
猜你喜欢
  • 2016-04-16
  • 1970-01-01
  • 1970-01-01
  • 2021-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-19
  • 1970-01-01
相关资源
最近更新 更多