所以我正在忙于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(已过滤)中将显示该数组。
但是现在我只想要“名称”显示在字符串上。我该怎么办?
您可以使用find
或filter
:
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)
索引会很有帮助。
console.log(filtered);
console.log(filtered[0].name);
过滤后使用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);
这是除了对方的答案之外的另一种方法,使用过滤器,映射然后加入。
datas.filter(data => data.location === "location1").map(d => d.name).join('')