检索如下JSON:
"JSON": [
{
"mySchool": "college",
"myHome": "apartment",
"myFavoriteSport": "soccer"
},
{
"mySchool": "highschool",
"myHome": "house",
"myFavoriteSport": "hockey"
},
{
"mySchool": "college",
"myHome": "box",
"myFavoriteSport": "soccer"
},
{
"mySchool": "elementary",
"myHome": "tent",
"myFavoriteSport": "soccer"
}
]
我该如何有条件地对其进行过滤,以便...如果soccer
是myFavoriteSport
键的值,然后返回包含myFavoriteSport: soccer
对的所有对象的数组?我确定我最终会将对象pushing
放入数组中,但是我不太了解如何将其分离出来,以便将其分配给变量。
我确定它会涉及某种类型的循环,但这是我第一次使用JSON和这种类型的对象,因此我不太确定如何处理它。
答案 0 :(得分:4)
如果要过滤,请使用.filter
-只需检查myFavoriteSport
属性是否为soccer
:
const input = {
"JSON": [
{
"mySchool": "college",
"myHome": "apartment",
"myFavoriteSport": "soccer"
},
{
"mySchool": "highschool",
"myHome": "house",
"myFavoriteSport": "hockey"
},
{
"mySchool": "college",
"myHome": "box",
"myFavoriteSport": "soccer"
},
{
"mySchool": "elementary",
"myHome": "tent",
"myFavoriteSport": "soccer"
}
]
};
console.log(
input.JSON.filter(({ myFavoriteSport }) => myFavoriteSport === 'soccer')
);
还请注意,JSON是一种以字符串格式表示对象 的方式。 (例如,
const myJSON = '[{"foo":"bar"},{"baz":"buzz"}]';
)。如果您有实际的对象/数组,则它不是JSON格式-只是一个普通对象。最好使用诸如arr
或personArr
之类的名称。 There's no such thing as a "JSON Object"
答案 1 :(得分:0)
使用filter()
数组方法很容易实现,有一个单一的解决方案:您可以在回调函数中指定一个条件,最后您将获得一个新的符合条件的数组。
const JSON = [
{
"mySchool": "college",
"myHome": "apartment",
"myFavoriteSport": "soccer"
},
{
"mySchool": "highschool",
"myHome": "house",
"myFavoriteSport": "hockey"
},
{
"mySchool": "college",
"myHome": "box",
"myFavoriteSport": "soccer"
},
{
"mySchool": "elementary",
"myHome": "tent",
"myFavoriteSport": "soccer"
}
];
const result = JSON.filter(item => item.myFavoriteSport === 'soccer');
console.log(result);
您还可以使用许多其他的数组迭代方法来获得这样的结果,但是filter
非常适合您的需求。