0

I have one url that give the output below in JSON:

{
    "categorias": [
        {
            "id_categoria": 1,
            "nom_categoria": "Graduação"
        },
        {
            "id_categoria": 2,
            "nom_categoria": "Pós-Graduação"
        },
        {
            "id_categoria": 3,
            "nom_categoria": "Disciplinas"
        }
    ]
}

How I can extract only the values "Graduação","Pós-Graduação","Disciplinas" using Jquery?

fabiobh
  • 705
  • 2
  • 13
  • 33

2 Answers2

1

use map function

var categoriesName = yourJsonResponse.categorias.map(function(category) { 
    return category.nom_categoria;
});

if it is a string (not an object), you will need to parse it first. You can do it by using JSON.parse() function

Gonzalo.-
  • 12,512
  • 5
  • 50
  • 82
1

Use Array#map and fat arrow functions.

let categorias = [
        {
            "id_categoria": 1,
            "nom_categoria": "Graduação"
        },
        {
            "id_categoria": 2,
            "nom_categoria": "Pós-Graduação"
        },
        {
            "id_categoria": 3,
            "nom_categoria": "Disciplinas"
        }
    ];
    
    let res = categorias.map(x=>x["nom_categoria"]);
    console.log(res);
Pankaj Shukla
  • 2,657
  • 2
  • 11
  • 18
  • Unfortunately this solution doesn't work for me, because I can't change the page that give me result. In this case you modify some things in the data, like insert the 'let' text and remove '{}' – fabiobh Jun 07 '17 at 12:26
  • @fabiobh No, it doesn't modify anything. This is just to give you an idea as to how you can do it! For example the solution is same as `var categoriesName = yourJsonResponse.categorias.map(x=>x["nom_categoria"]);`. It's just shorter. It is called terse code. With ES6 people are now preferring this syntax over `function` syntax. – Pankaj Shukla Jun 07 '17 at 13:17
  • it works. I understand now, I think it's a better solution because I need to write less code and I consider that is more readable. – fabiobh Jun 08 '17 at 14:08