【问题标题】:Getting particular value out of a JSON object in an array从数组中的 JSON 对象中获取特定值
【发布时间】:2019-10-08 02:19:43
【问题描述】:

从数组中的 JSON 对象中获取特定信息。我有两个同名的钥匙,每次都会改变它们的位置“汽车的“名称”字段可能处于不同的位置。 如果位置发生变化,如何仅获得 Redcar(Redcar 不是恒定的)

{
    "links": [],
    "content": [
        {
          "name": "Redcar",
          "color":"red"
         },
        {
         "name":"Eric",
          "Age":"25"
       }
      ]
}

【问题讨论】:

  • myJsonObj.content[0].name?你总是想得到 Redcar 对象吗?
  • 是的,Redcar 对象在不同的​​位置(1 或 0)
  • 请创建一个minimal reproducible example,输入正确,预期输出带有清晰的问题陈述。 “汽车的名称字段可能在不同的位置“redcar会因每次迭代而变化”到底是什么意思。你的问题不清楚

标签: javascript json powershell


【解决方案1】:

使用Array.find()

let data = {
  "links": [],
  "content": [
      {
        "name": "Redcar",
        "color":"red"
      },
      {
       "name":"Eric",
       "Age":"25"
      }
   ]
}

let car = data.content.find(x => {return x.name == "Redcar"});

console.log(car);

【讨论】:

  • redcar 会因每次迭代或 API 调用而变化
  • @karan 你是什么意思它会变化?要具体。
  • redcar 可能会更改为卡车、货车、SUV...等
  • @karan 好吧,也许你应该把这部分添加到你的问题中。如果您不知道要查找的内容,则无法在数组中找到某些内容。就问题而言,我已经给了你一个可以接受的答案。
【解决方案2】:

如果位置可以更改,那么您将需要使用 .find() 搜索数组

let theRedCar = array.content.find( item => item.name === "Redcar" )

// theRedCar = { name: 'Redcar', color: 'red' }

【讨论】:

  • redcar 会因每次迭代或 API 调用而变化
【解决方案3】:

不清楚你在追求什么。

Powershell

## Q:\Test\2019\05\21\SO_56242505.ps1
$Json = @"
{
    "links": [],
    "content": [
        {
          "name": "Redcar",
          "color":"red"
         },
        {
         "name":"Eric",
          "Age":"25"
       }
      ]
}
"@ | ConvertFrom-Json

$Json.content | Where-Object Name -eq 'Redcar'

样本输出

name   color
----   -----
Redcar red

【讨论】:

    猜你喜欢
    • 2017-11-22
    • 2018-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-13
    • 1970-01-01
    相关资源
    最近更新 更多