从JSON字符串Javascript中删除外部索引

时间:2017-05-12 11:20:36

标签: javascript json

我在JavaScript中有以下JSON字符串:

{
 "0":
   {"race":"Race1","sum":"13.7","color":"#BEBEBE"},
 "1":
   {"race":"Race2","sum":"20.3","color":"#B03060"},
 "2":
   {"race":"Race3","sum":"35.2","color":"#FFFF01"},
 "3":
   {"race":"Race4","sum":"31.3","color":"#4A6FE3"},
 "4":
   {"race":"Unknown","sum":0,"color":"#9ACD32"}
}

我需要将其转换为:

  

已编辑的示例

[{"race":"Race1","sum":"13.7","color":"#BEBEBE"},
  {"race":"Race2","sum":"20.3","color":"#B03060"},
  {"race":"Race3","sum":"35.2","color":"#FFFF01"},
  {"race":"Race4","sum":"31.3","color":"#4A6FE3"},
  {"race":"Unknown","sum":0,"color":"#9ACD32"}]

有什么方法可以实现这个目标吗?

2 个答案:

答案 0 :(得分:3)

您可以简单地解析并获取这样的值..

var jsonStr = '{"0":{"race":"Race1","sum":"13.7","color":"#BEBEBE"},"1":{"race":"Race2","sum":"20.3","color":"#B03060"},"2":{"race":"Race3","sum":"35.2","color":"#FFFF01"},"3":{"race":"Race4","sum":"31.3","color":"#4A6FE3"},"4":{"race":"Unknown","sum":0,"color":"#9ACD32"}}';

var json = Object.values(JSON.parse(jsonStr));
console.log(json)

答案 1 :(得分:1)

你可以在一个没有键的对象中拥有对象,你应该在数组中处理它们或者它处于原始状态

如果您想要修改,请使用Object.key(obj)然后循环所有键



var obj = {
 "0":
   {"race":"Race1","sum":"13.7","color":"#BEBEBE"},
 "1":
   {"race":"Race2","sum":"20.3","color":"#B03060"},
 "2":
   {"race":"Race3","sum":"35.2","color":"#FFFF01"},
 "3":
   {"race":"Race4","sum":"31.3","color":"#4A6FE3"},
 "4":
   {"race":"Unknown","sum":0,"color":"#9ACD32"}
}

var arr = [];

Object.keys(obj).forEach(function(item) {
  arr.push(obj[item]);
})

console.log(arr);




或者使用地图@trincot也建议



var obj = {
 "0":
   {"race":"Race1","sum":"13.7","color":"#BEBEBE"},
 "1":
   {"race":"Race2","sum":"20.3","color":"#B03060"},
 "2":
   {"race":"Race3","sum":"35.2","color":"#FFFF01"},
 "3":
   {"race":"Race4","sum":"31.3","color":"#4A6FE3"},
 "4":
   {"race":"Unknown","sum":0,"color":"#9ACD32"}
}


var arr = Object.keys(obj).map(function(item) {
  return obj[item]
})

console.log(arr);




然而,最简单的方法是使用Object.values(obj)



var obj = {
 "0":
   {"race":"Race1","sum":"13.7","color":"#BEBEBE"},
 "1":
   {"race":"Race2","sum":"20.3","color":"#B03060"},
 "2":
   {"race":"Race3","sum":"35.2","color":"#FFFF01"},
 "3":
   {"race":"Race4","sum":"31.3","color":"#4A6FE3"},
 "4":
   {"race":"Unknown","sum":0,"color":"#9ACD32"}
}




console.log(Object.values(obj));