如何从json文件中选择和打印值

问题描述 投票:0回答:1

我有这个json文件。如何仅查看版本为“ A”的项目?非常感谢。

[
    {
      "id": 1,
      "version": "A",
      "description": "description 01",
      "title": "title 01"
    },
    {
      "id": 2,
      "version": "B",
      "description": "description 02",
      "title": "title 02"
    },
    {
      "id": 3,
      "version": "A",
      "description": "description 03",
      "title": "title 03"
    }
]

我不知道如何写所有值,但不知道如何只写“ A”。

javascript json qml blackberry blackberry-10
1个回答
0
投票

您可以使用filter方法

const items = [
    {
      "id": 1,
      "version": "A",
      "description": "description 01",
      "title": "title 01"
    },
    {
      "id": 2,
      "version": "B",
      "description": "description 02",
      "title": "title 02"
    },
    {
      "id": 3,
      "version": "A",
      "description": "description 03",
      "title": "title 03"
    }
];

const versionAItems = items.filter( item => item.version === 'A' )
console.log(versionAItems)

0
投票

如果只想查找与版本匹配的项目,则可以使用find方法,如下所示:

let obj = 
[
    {
      "id": 1,
      "version": "A",
      "description": "description 01",
      "title": "title 01"
    },
    {
      "id": 2,
      "version": "B",
      "description": "description 02",
      "title": "title 02"
    },
    {
      "id": 3,
      "version": "A",
      "description": "description 03",
      "title": "title 03"
    }
];
let find =  "A";
let result = obj.find((item)=> item.version === find);
console.log(result);
© www.soinside.com 2019 - 2024. All rights reserved.