如何获取数组中的所有json键

时间:2017-09-18 12:38:31

标签: javascript angularjs arrays json

我有一个具有以下结构的JSON对象

{"30-31":[{"msg":"hello","usr":"31"}],
"33-30":[{"msg":"shah hi","usr":"30"}]}

我可以执行哪些操作来获取此["30-31", "33-30"]之类的数组。 我尽力使用.map等,但没有成功,有人可以帮忙吗?

2 个答案:

答案 0 :(得分:5)

您可以使用Object.keys()



let obj = {"30-31":[{"msg":"hello","usr":"31"}],
  "33-30":[{"msg":"shah hi","usr":"30"}]}
  
console.log(Object.keys(obj));




答案 1 :(得分:4)

您可以使用内置Object.keys(obj)

var json = {"30-31":[{"msg":"hello","usr":"31"}],
            "33-30":[{"msg":"shah hi","usr":"30"}]};
var keys = Object.keys(json);
console.log(keys);

此外,您可以使用for...in循环以硬(跨浏览器)方式执行此操作:

var json = {"30-31":[{"msg":"hello","usr":"31"}],
            "33-30":[{"msg":"shah hi","usr":"30"}]};
var keys = [];
for (k in json) keys.push(k);
console.log(keys);