格式化json对象数组

时间:2016-08-12 09:32:54

标签: javascript angularjs

我正在尝试制作一个json对象数组。

我的数组是

var array=[{a:1,b:2,id:apple},{a:5,b:10,id:banana}]

我想输出它,以便数组格式为:

[{source:apple, target:a ,value:1},{source:apple, target:b ,value:2},{source:banana, target:a ,value:5},{source:banana, target:b ,value:10}]

帮助赞赏!!

3 个答案:

答案 0 :(得分:0)

只需使用 $result = ModelClass:: where('d_expiryDate ','>=',$current_time) ->where('d_expiryDate ','<=',$one_month_interval ) ->get(); return $result ;

即可

答案 1 :(得分:0)

您可以使用reduce()Object.keys()来获得此结果。

&#13;
&#13;
var array=[{a:1,b:2,id:'apple'},{a:5,b:10,id:'banana'}];

var result = array.reduce(function(r, e) {
  Object.keys(e).forEach(function(k) {
    if(k != 'id') r.push({source: e.id, target:k ,value:e[k]}) 
  })
  return r;
}, []);

console.log(result)
&#13;
&#13;
&#13;

答案 2 :(得分:0)

原生(未经测试)的解决方案是:

&#13;
&#13;
function myFormat(objects){
  var formated = [];
  for(var i = 0; i < objects.length; i++){
    if(!objects[i].hasOwnProperty('id'))continue;

    var fObj = [];
    for(var key in objects[i]){
      if(key == 'id')continue;

      formated.push({
        source: objects[i].id, 
        target: key, 
        value: objects[i][key]
      });
    }
  }
  return formated;
}

var array=[{a:1,b:2,id:'apple'},{a:5,b:10,id:'banana'}];
console.log(myFormat(array));
&#13;
&#13;
&#13;