BeckiD
BeckiD

Reputation: 315

get data from javascript object

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

Answers (4)

Nikhil Sengar
Nikhil Sengar

Reputation: 101

var t = {"Cats":10,"Dogs":815,"Fishes":2};
for (var key in t)
{
  console.log(key, t[key]);
}

Upvotes: 1

Pranav C Balan
Pranav C Balan

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

Nina Scholz
Nina Scholz

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

Đào Minh Hạt
Đào Minh Hạt

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

Related Questions