JavaScript:根据键的值有条件地过滤JSON?[重复]

pbpqsu0x  于 12个月前  发布在  Java
关注(0)|答案(2)|浏览(193)

此问题在此处已有答案

Find object by id in an array of JavaScript objects(37个答案)
5年前关闭。
在检索这样的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"
}
]

字符串
我如何有条件地过滤它,以便.如果soccermyFavoriteSport键的值,那么返回一个包含myFavoriteSport: soccer对的所有对象的数组?我肯定我会在最后将pushing对象放入数组,但我不太知道如何将其单独出来,以便将其分配给变量。
我确信它会涉及到某种类型的循环,但这是我第一次使用JSON和这种类型的对象,所以我有点不确定如何处理它。

w46czmvw

w46czmvw1#

如果你想过滤,那么使用.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格式的-它只是一个普通的对象。最好将键命名为arrpersonArr或类似的东西。There's no such thing as a "JSON Object"

o0lyfsai

o0lyfsai2#

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完全符合您的需求。

相关问题