Search code examples
javascriptjsonresponsekey-value

How can i get a value from a JSON object with no key


I am making a http request and then I get values from a SQL table.

router.get('/', function(req, res, next) {
    controller.getAllPosts( function(err,posts){
        if(err){
            res.status(500);
            res.end();
        }else{           
            res.json(posts);
}

The response I get is like this:

[
  {
    "id_post": 1,
    "description": "Hola",
    "username": "jumavipe",
    "image": "1.jpg"
  },
  {
    "id_post": 2,
    "description": "no se",
    "username": "jacksonjao",
    "image": "2.jpg"
  },
  {
    "id_post": 3,
    "description": "nuevo tatuaje de bla bla bla",
    "username": "jumavipe",
    "image": "3.jpg"
  }
]

How do I get only the description from post 3

I can't do:

var desc= posts[2].description

I looked online and I tried something like this:

var description = posts.getJSONObject("LabelData").getString("description");

What should I use as a parameter in the getJSONObject() if my json array doesn't have a key.

I can't find something that works. How can I get that value from one object from the json array?


Solution

  • Using Array.prototype.find

    If you don't have any browser compatibility issues, you can use Array.prototype.find

    var posts = [
      {
        "id_post": 1,
        "description": "Hola",
        "username": "jumavipe",
        "image": "1.jpg"
      },
      {
        "id_post": 2,
        "description": "no se",
        "username": "jacksonjao",
        "image": "2.jpg"
      },
      {
        "id_post": 3,
        "description": "nuevo tatuaje de bla bla bla",
        "username": "jumavipe",
        "image": "3.jpg"
      }
    ];
    
    var post = posts.find(function(item) {
      return item.id_post == 3;
    });
    
    console.log(post.description);
    

    Using Array.prototype.filter

    Array.prototype.filter is supported in almost most of the browsers and it will work.

    var selected_posts = posts.filter(function(item) {
      return item.id_post == 3;
    });
    
    console.log(selected_posts[0].description);