Q:

How to get an element based on their key with JavaScript

I have a JSON response that looks like this, and I would like to get all the posts of this user that have a state 2:
user = {
  "name": "John",
  "posts": [
    {
      id: 1,
      state: 1,
      title: "Hello"
    },
    {
      id: 2,
      state: 1,
      title: "Hi"
    },
    {
      id: 3,
      state: 2,
      title: "World"
    },
    {
      id: 4,
      state: 3,
      title: "Hey"
    },
    {
      id: 5,
      state: 2,
      title: "Goodbye"
    }
  ]
}

How can I do that?
I would like to have my response something like this
result = {
  {
    id: 3,
    state: 2,
    title: "World"
  },
  {
    id: 5,
    state: 2,
    title: "Goodbye"
  },
}

A:

Your post inside user does not contain valid objects (missing , after each objects).
Try with Array's filter():

var user = {
  "name": "John",
  "posts": [
    {
      id: 1,
      state: 1,
      title: "Hello"
    },
    {
      id: 2,
      state: 1,
      title: "Hi"
    },
    {
      id: 3,
      state: 2,
      title: "World"
    },
    {
      id: 4,
      state: 3,
      title: "Hey"
    },
    {
      id: 5,
      state: 2,
      title: "Goodbye"
    }
  ]
}

var state2Post = user.posts.filter(p => p.state == 2);

console.log(state2Post);

