一、数据源

var arr = [
    {"id":"1001","name":"值1","value":"111"},
    {"id":"1001","name":"值1","value":"11111"},
    {"id":"1002","name":"值2","value":"25462"},
    {"id":"1002","name":"值2","value":"23131"},
    {"id":"1002","name":"值2","value":"2315432"},
    {"id":"1003","name":"值3","value":"333333"}
];

二、处理逻辑

var map = {},
    dest = [];
for(var i = 0; i < arr.length; i++){
    var ai = arr[i];
    if(!map[ai.id]){
        dest.push({
            id: ai.id,
            name: ai.name,
            data: [ai]
        });
        map[ai.id] = ai;
    }else{
        for(var j = 0; j < dest.length; j++){
            var dj = dest[j];
            if(dj.id == ai.id){
                dj.data.push(ai);
                break;
            }
        }
    }
}

三、结果

console.log(dest);

备注:

工作中遇到的情况:如果只通过”title“查找,ts做类型检查,则使用方式如下,在此记录:

 const onSearch = (value) => {
    let map = {}, dest: any[] = [];
    for (var i = 0; i < data.length; i++) {
      var ai = data[i];
      if (!map[ai['title']]) {
        dest.push({
          title: ai['title'],
          data: [ai]
        });
        map[ai['title']] = ai;
      } else {
        for (var j = 0; j < dest.length; j++) {
          var dj = dest[j];
          if (dj.title === ai['title']) {
            dj.data.push(ai);
            break;
          }
        }
      }
    }
打印查看结果:

原数据:

console.log('dest', dest);

扩展

ts做类型检查的时候,有时候报以下错:

一般是因为前面没有给这个list指定具体的属性名称,解决办法是直接在后面加上[“name”]这样的属性名进行调用:

您已经阅读00:00:00欢迎留言评论,喜欢的话就为作者点个赞或者赏颗糖吧! 分享