How to extract only JSON values by removing keys

Asked

Viewed 400 times

-2

I have an array with some ids, the return object of my request to Webservice is as shown in code snippet number 1.

I wanted to know if you have any way via jQuery, to extract only the values and leave my JSON as shows the object of the second snippet of code:

  1. How are you:

       [{
                "id": "1"
            }, {
                "id": "2"
            }, {
                "id": "3"
            }, {
                "id": "4"
            }, {
                "id": "5"
            }]
    
  2. How I wish you were:

    ["1","2","3","4","5"]
    
  • It is necessary to first transform the string into an object, using for example JSON.parse() and then vc can go through the array and get the ids.

  • But it is already in JSON format, I made the request to the web service via angular and it returns me using echo json_encode($reply)

1 answer

2


You can use the method Array.map to extract only the ids.

Example:

let dados = [
    { "id": "1" },
    { "id": "2" },
    { "id": "3" },
    { "id": "4" },
    { "id": "5" }
];

let ids = dados.map(item => item.id);

console.log(ids);

If you can’t use Arrow functions, another example:

var dados = [
    { "id": "1" },
    { "id": "2" },
    { "id": "3" },
    { "id": "4" },
    { "id": "5" }
];

var ids = dados.map(function(item) {
    return item.id;
});

console.log(ids);

  • Thank you very much was that, I used some wrong term or there is something I can improve the question for those who search understand more clearly and objectively?

  • You can exchange "I have a JSON" for "I have an array". It makes no difference where it came from, your question is how to extract the data from this array to another

Browser other questions tagged

You are not signed in. Login or sign up in order to post.