如何在没有名字的情况下迭代json

时间:2014-11-19 22:57:55

标签: javascript

var categories= {
  "art": 352,
  "health-beauty": 358,
  "home": 372,
  "jewelry": 339,
  "kids": 320

}
for(var i in categories)
{
    console.log("name: " + i + "id: " + ?);
}

我尝试将类别和ID的名称导入到mongodb但是很难获得如何获取每个值的ID?这是可能的还是我必须手动重新排列JSON文件?

1 个答案:

答案 0 :(得分:0)

您的var i包含属性,并且可以使用arraylike表示法访问对象的属性。这样:

for(var i in categories) {
    console.log("name: " + i + "id: " + categories[i]);
}

我建议你总是把你的花括号放在右边,因为不这样做会产生意想不到的结果:

function someFunction () 
{ 
  return 
  { 
    prop: "Prop" 
  } 
}

alert(someFunction().prop); // Error, it returned undefined because something called semi-colon insertion. Read about it.