首页 > 合并后的json如何加入key

合并后的json如何加入key

之前提出过一个如何循环请求json的问题,然后各位好心人帮忙解决了,现在继那个问题出现了另外一个问题。合并后的json键入key
下方是循环请求的代码

var api_domain = *** ,
  api = {
    search: {
      artist: api_domain + 'search/musician',
      music: api_domain + 'search/music',
      playlist: api_domain + 'search/playlist',
    },
  }
  
function search(keyword) {
  var result = $.map(api.search, function(url, type) {
      return $.get(url, {
        'keyword': keyword,
        'page': 1,
        'page_count': 20,
      })
    })
  $.when.apply(null, result).done(function() {
    var data = new Object
    $.extend(true, data, arguments);
    console.log(data);
  })
}

现在的问题是如何将红框里的3个object合并成格式

type1: { object... },
type2: { object... } ,
type3: { object... } //object指下图红框里的object,type指map循环时的type


var arr=[
{a:1,b:9,type:"A"},
{a:2,b:10,type:"B"},
{a:3,b:11,type:"C"},
]

var result={};
arr.forEach(function(item,index){
    if(!result[item.type]){
        result[item.type]=[];
    }
    result[item.type].push(item);
});

console.log(result);

结合 @kikong 给到的思路写出来了!

function search(keyword) {
  var n = 0,
    result = $.map(api.search, function(url, type) {
      n++
      return [type, $.get(url, {
        'keyword': keyword,
        'page': 1,
        'page_count': 20,
      })]
    })
  $.when.apply(null, result).done(function() {
    for (var data = {}, i = 0; i < n; i++) data[arguments[i * 2]] = arguments[i * 2 + 1][0]
    console.log(data);
  })
}
【热门文章】
【热门文章】