最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

get data from javascript object - Stack Overflow

programmeradmin2浏览0评论

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 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?

Share Improve this question asked Mar 8, 2017 at 8:15 BeckiDBeckiD 3151 gold badge3 silver badges16 bronze badges 1
  • t[key] => yourObject[keyName] developer.mozilla/en-US/docs/Web/JavaScript/Guide/… – Thirueswaran Rajagopalan Commented Mar 8, 2017 at 8:22
Add a ment  | 

4 Answers 4

Reset to default 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);

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

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

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

评论列表(0)

  1. 暂无评论