Reputation: 315
I have weird object:
{"Cats":10,"Dogs":815,"Fishes":2}
How can I get full value from each piece of data
var t = {"Cats":10,"Dogs":815,"Fishes":2};
var keys = [];
for (var key in t) {
if (t.hasOwnProperty(key)) {
console.log(key)
}
}
I'm getting only the names without number I can use JSON.stringify and then manipulate that object but maybe there is other way? Probably I missing something?
Upvotes: 1
Views: 15223
Reputation: 101
var t = {"Cats":10,"Dogs":815,"Fishes":2};
for (var key in t)
{
console.log(key, t[key]);
}
Upvotes: 1
Reputation: 115212
the for...in
statement iterate over the property names get the value by property name.
var t = {"Cats":10,"Dogs":815,"Fishes":2};
var keys = [];
for (var key in t) {
if (t.hasOwnProperty(key)) {
console.log(key, t[key])
}
}
If you would like to generate an array of values then use Object.keys
and Array#map
methods.
var t = { "Cats": 10, "Dogs": 815, "Fishes": 2};
var keys = Object.keys(t);
var values = keys.map(function(key) {
return t[key];
});
console.log(keys, values);
Upvotes: 2
Reputation: 386550
You could get the own properties first with Object.keys
and iterate then.
var t = { Cats: 10, Dogs: 815, Fishes: 2 },
keys = Object.keys(t);
keys.forEach(function (key) {
console.log(key, t[key]);
});
Upvotes: 1
Reputation: 2930
var t = {"Cats":10,"Dogs":815,"Fishes":2};
var keys = [];
for (var key in t) {
if (t.hasOwnProperty(key)) {
console.log(key, t[key])
}
}
Upvotes: 2