从数组中的JSON对象中获取特定值

时间:2019-05-21 16:17:10

标签: javascript json powershell

从数组中的JSON对象中获取特定内容。如果我有两个具有相同名称的钥匙,则每次汽车的“名称”字段可能位于不同位置时,它们的位置都会有所不同。 如果位置改变,如何只获得Redcar(Redcar不是常数)

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

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

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

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

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

答案 2 :(得分:0)

目前尚不清楚你在追求什么。

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
相关问题