在javascript中从数组生成多级对象

我有一系列事件,我想在这些数组的对象之间建立关系.

数组:

[{
    'area': 'punjab',
    'site': 'lahore',
    'link': 'http: //lahore.com'
}, {
    'area': 'punjab',
    'site': 'sargodha',
    'link': 'http: //sargodha.com'
}, {
    'area': 'punjab',
    'site': 'multan',
    'link': 'http: //multan.com'
} {
    'area': 'sindh',
    'site': 'karachi',
    'link': 'http: //karachi.com'
}]

知道我想让关系变得像

 {
  "area": "punjab",
  "site": [
    {
      "name": "lahore",
      "link": [
        {
          "name": "http://sargodha.com",
        }
      ]
    },
   {
      "name": "sargodha",
      "link": [
        {
          "name": "http://sargodha.com",
        }
      ]
    }
  ]
},
{
  "area": "sindh",
  "site": [
    {
      "name": "karachi",
      "link": [
        {
          "name": "http://karachi.com",
        }
      ]
    }
}

这是我写的代码:

    function isinarrayfilters(matchingObject, targetArray, key) {
    var existindex = -1;
    $.each(targetArray, function(index, array) {
        if (array.key == matchingObject.key) {
            //Object exist in array
            existindex = index;
        }
    });
    return existindex;
}

generatedRelationArray = [];
        $.each(alertsJson, function(index, alertJson) {
            inarrayindex = isinarrayfilters(alertJson.area, relationArray,'area');
            if (inarrayindex == -1) {
                key = alertJson.site
                generatedsites = {
                    "area": alertJson.area,
                    "site": []
                }
                relationArray.push(generatedsites);
            }
        });

知道有人指导我如何将网站添加到相关区域.

>我必须再次运行循环并尝试检查存在的方法并获取索引并将网站推入其中?

最佳答案 格式保留答案:

var generate = function(list) {
  var resultList = [];
  var tmpStoreRef = {};

  $.each(list, function(id, item) {
    var area = item.area
        ,site = item.site
        ,link = item.link;
    if (typeof tmpStoreRef[area] === 'undefined') {
      tmpStoreRef[area] = {
        area: area,
        site: []
      }
      resultList.push(tmpStoreRef[area]);
    }
    tmpStoreRef[area].site.push({
      name: site,
      link: link
    });
  });

  return resultList;
};
点赞