如何从过滤的json数组中获取值

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

所以我正在忙于React,我过滤了一个json数组,但现在我只想从该过滤的json数组中获取一个值。

让我解释一下,我在json数组中有这个

{
  name:"name1"
  location:"location1"
  job:"job1"
},
{
  name:"name2"
  location:"location2"
  job:"job2"
},

我已过滤

        var filtered = datas.filter(data => data.location == "location1")

现在在console.log(已过滤)中将显示该数组。

但是现在我只想要“名称”显示在字符串上。我该怎么办?

javascript arrays reactjs
4个回答
0
投票

您可以使用findfilter

const datas = [
  {
    name: 'name1',
    location: 'location1',
    job: 'job1',
  },
  {
    name: 'name2',
    location: 'location2',
    job: 'job2',
  },
]

const found = datas.find(data => data.location === 'location1')
const filtered = datas.filter(data => data.location === 'location1')

console.log(found && found.name)
console.log(filtered[0] && filtered[0].name)

0
投票

索引会很有帮助。

console.log(filtered);
console.log(filtered[0].name);

0
投票

过滤后使用Array.map()仅存储name字段。

const data = [{
    name: "name1",
    location: "location1",
    job: "job1"
  },
  {
    name: "name2",
    location: "location2",
    job: "job2"
  }
];

const results = data
  .filter(d => d.location === "location1")
  .map(d => d.name); // only store name field

console.log(results);

0
投票

这是除了对方的答案之外的另一种方法,使用过滤器,映射然后加入。

datas.filter(data => data.location === "location1").map(d => d.name).join('')
© www.soinside.com 2019 - 2024. All rights reserved.