mheonyae
mheonyae

Reputation: 633

Get specific values from response

I get this ajax response:

{"0":{"id":1,"value":"73.0","tracker_id":1,"created_at":"2020-05-04 20:13:22","updated_at":"2020-05-04 20:13:22"},"7":{"id":8,"value":"73.0","tracker_id":1,"created_at":"2020-05-03 20:13:22","updated_at":"2020-05-04 20:13:22"},"8":{"id":9,"value":"73.0","tracker_id":1,"created_at":"2020-05-06 19:48:31","updated_at":"2020-05-06 19:48:31"}}

And i would like to extract only the values from each row. This obviously didnt work:

for (i = 0; i < data.length; i++) {
    console.log(data[i].value);
}

Upvotes: 1

Views: 295

Answers (5)

Mehdi Khoshnevis
Mehdi Khoshnevis

Reputation: 310

you can use for in loop to map objects:

const data = {"0":{"id":1,"value":"72.0","tracker_id":1,"created_at":"2020-05-04 20:13:22","updated_at":"2020-05-04 20:13:22"},"7":{"id":8,"value":"73.0","tracker_id":1,"created_at":"2020-05-03 20:13:22","updated_at":"2020-05-04 20:13:22"},"8":{"id":9,"value":"74.0","tracker_id":1,"created_at":"2020-05-06 19:48:31","updated_at":"2020-05-06 19:48:31"}};

for (key in data) {
  console.log(data[key].value);
}

Upvotes: -1

Mickael B.
Mickael B.

Reputation: 5215

You can useObject.values and map:

const data = {"0":{"id":1,"value":"73.0","tracker_id":1,"created_at":"2020-05-04 20:13:22","updated_at":"2020-05-04 20:13:22"},"7":{"id":8,"value":"73.0","tracker_id":1,"created_at":"2020-05-03 20:13:22","updated_at":"2020-05-04 20:13:22"},"8":{"id":9,"value":"73.0","tracker_id":1,"created_at":"2020-05-06 19:48:31","updated_at":"2020-05-06 19:48:31"}}

const value = Object.values(data).map(e => e.value)

console.log(value)

Upvotes: 2

Md Nazmul Hossain
Md Nazmul Hossain

Reputation: 2933

Try with This:

Object.values(a).map(p => console.log(p.value));

Upvotes: -1

caiopsilva
caiopsilva

Reputation: 19

should have a better solution, but it works

const values = Object.values(json).map(({ value})  => value)

Upvotes: 2

Ikechukwu Eze
Ikechukwu Eze

Reputation: 3161

I suppose the response has already been parsed.If you want to loop as in your example through each item,

const result = Object.values(data);
for (i = 0; i < result.length; i++) {
           console.log(result[i].value);
    }

Upvotes: 0

Related Questions