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 ??
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
const data = {"name": "John", "age": 30, "city": "New York"}
Object.entries(data).forEach(([k, v], i) => console.log(i, k, v))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With