使用javascript转换JSON结构

时间:2016-09-21 08:51:31

标签: javascript jquery json

任何人都可以帮助我使用arrayJSON

转换javascript jquery以下的[ [{"day1":10,"day2":154,"day3":24,"day4":48,"day5":154,"day6":48,"day7":154,"name":"Packet"}], [{"day1":10,"day2":154,"day3":24,"day4":48,"day5":154,"day6":48,"day7":154,"name":"car"}], [{"day1":10,"day2":154,"day3":24,"day4":48,"day5":154,"day6":48,"day7":154,"name":"bike"}] ]
[
{"name":"Packet","date":"Day1","value":10},
{"name":"Packet","date":"Day2","value":154},
{"name":"Packet","date":"Day3","value":24},
{"name":"Packet","date":"Day4","value":48},
{"name":"Packet","date":"Day5","value":154},
{"name":"Packet","date":"Day6","value":48},
{"name":"Packet","date":"Day7","value":154},

{"name":"car","date":"Day1","value":10},
{"name":"car","date":"Day2","value":154},
{"name":"car","date":"Day3","value":24},
{"name":"car","date":"Day4","value":48},
{"name":"car","date":"Day5","value":154},
{"name":"car","date":"Day6","value":48},

{"name":"bike","date":"Day1","value":10},
{"name":"bike","date":"Day2","value":154},
{"name":"bike","date":"Day3","value":24},
{"name":"bike","date":"Day4","value":48},
{"name":"bike","date":"Day5","value":154},
{"name":"bike","date":"Day6","value":48},]`

进入

JS

请提供任何帮助或任何我可以得到一些提示的例子....因为我是<div> <p style="font-size=40px;"> <b>Hello there, welcome</b> <br/> To this website </p> <p>Some other text</p> 的新手。

2 个答案:

答案 0 :(得分:1)

你可以这样做。

&#13;
&#13;
var array = [
  [{ "day1": 10,"day2": 154,"day3": 24,"day4": 48,"day5": 154,"day6": 48,"day7": 154,"name": "Packet" }],
  [{ "day1": 10,"day2": 154,"day3": 24,"day4": 48,"day5": 154,"day6": 48,"day7": 154,"name": "car" }],
  [{ "day1": 10,"day2": 154,"day3": 24,"day4": 48,"day5": 154,"day6": 48,"day7": 154,"name": "bike" }]
];

function convert(array) {
  if (!array instanceof Array && array.length === 0) {
    return array;
  }
  
  var result = [];
  for (var i = 0; i < array.length; i++) {
    var item = array[i][0];
    var name = item.name;
    
    for (var key in item) {
      if (key === 'name') {
      	continue;
      }
      
      result.push({ "name": name,"date": key,"value": item[key]});
    }
  }
  
  return result;
}

var result = convert(array);
console.log(result);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

var inp = [ 
          [{"day1":10,"day2":154,"day3":24,"day4":48,"day5":154,"day6":48,"day7":154,"name":"Packet"}],
          [{"day1":10,"day2":154,"day3":24,"day4":48,"day5":154,"day6":48,"day7":154,"name":"car"}],
          [{"day1":10,"day2":154,"day3":24,"day4":48,"day5":154,"day6":48,"day7":154,"name":"bike"}]
          ];

var res=[];
inp.map(x=>x.map(y=>{for(z in y) {if (z!='name')  res.push({"name":y.name, "date":z,"value":y[z] });}}));
JSON.stringify(inp);