-1

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?

Joshua
  • 40,822
  • 8
  • 72
  • 132
  • 4
    indexing starts from 0, so you need `posts[2].description` instead. – raina77ow Apr 24 '17 at 19:47
  • 1
    And note that this has nothing to do with JSON. By the time you're trying to access that value, you're accessing an array of objects, not a *string*. JSON is a textual notation. You only deal with *JSON* in JavaScript if you're dealing with a *string*. – T.J. Crowder Apr 24 '17 at 19:49
  • 1
    *"i looked online and i tried something like this"* Those were apparently Java resources. Java != JavaScript. – T.J. Crowder Apr 24 '17 at 19:49
  • Do you mean to say "How do I get only the description from the post where `id_post` is 3? – Tibrogargan Apr 24 '17 at 19:53
  • Related: [Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/q/11922383/218196) – Felix Kling Apr 24 '17 at 20:10

1 Answers1

2

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);
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60