gpt4 book ai didi

javascript - 过滤 JSON 对象

转载 作者:行者123 更新时间:2023-11-30 09:30:34 27 4
gpt4 key购买 nike

我正在从 XMLHttpRequest 中获取一个 JSON 对象,并且正在寻找一种解决方案来过滤 bt genre。如果未传递可过滤参数,我还需要一种返回所有结果(未过滤)的方法。

app.js(伪函数)

function filterObject(json, filterBy) {
// filter through json
// return item that matches filterBy
}

data.json

[{
"date": {
"dayOfWeek": "Thursday",
"month": "Oct"
},
"location": "Bristol",
"genre": "rock"
}, {
"date": {
"dayOfWeek": "Cardiff",
"dayOfMonth": 13,
"month": "Oct"
},
"location": "Manchester",
"genre": "jazz"
}]

最佳答案

您可以使用 array#filter 根据 genre 值过滤您的 json。

var json = [{"date": {"dayOfWeek": "Thursday","month": "Oct"},"location": "Bristol","genre": "rock"}, {"date": {"dayOfWeek": "Cardiff","dayOfMonth": 13,"month": "Oct"},"location": "Manchester", "genre": "jazz"}];

function filterObject(json, filterBy) {
return filterBy ? json.filter(o => o.genre === filterBy) : json;
}

console.log(filterObject(json,'jazz'));

console.log(filterObject(json));
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 过滤 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46533171/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com