Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get json key and value by index instead of their names

Here's my Json

var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');

I can get the values of the json by using it's key like console.log(obj.name);

But I want to get the values by index instead of a key something like console.log(obj[0]);

this guy here said it's not good because the JSON are unordered but In my case the order will always be same no matter what.

$.each(obj ,function(i,item){
    console.log(i+' '+item);
});

The above code will return the keys and values all at once but I want to show it one by one.

If I can get the values by index it will be very helpful for me to show the data to user.

So is it possible ??

like image 252
Cybertronian Avatar asked Oct 14 '25 20:10

Cybertronian


2 Answers

You can transform the values into an array with Object.values, and then get the index you want:

var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}')
console.log(obj.name) // John
var array = Object.values(obj)
console.log(array[0]) // John
like image 131
Max Avatar answered Oct 17 '25 10:10

Max


const data = {"name": "John", "age": 30, "city": "New York"}
Object.entries(data).forEach(([k, v], i) => console.log(i, k, v))
like image 39
kornieff Avatar answered Oct 17 '25 10:10

kornieff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!