1

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?

1

4 Answers 4

2

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);

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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]);
});

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.