Deep Flatten JavaScript Object Recursively

后端 未结 14 2190
囚心锁ツ
囚心锁ツ 2021-02-18 20:34

Data:

var data = [
    {
      \"id\": 1,
      \"level\": \"1\",
      \"text\": \"Sammy\",
      \"type\": \"Item\",
      \"items\": [
               


        
14条回答
  •  迷失自我
    2021-02-18 21:01

    This solution should work on IE11; uses filter, map, and reduce.

    var item = function(x) {
        return {
            "id": x.id,
            "level": x.level,
            "text": x.text,
            "type": x.type,
            "items": x.items ? [] : null
        }
    }
    
    var flatten = function(a, b) {
        return a.concat(b);
    };
    
    var onlyUnique = function(acc, curr) {
        if (acc.length == 0) {
            acc.push(curr);
        } else {
            var search = acc.filter(function(x){return x.id===curr.id;})
            if (search.length == 0) {
                acc.push(curr);
            }
        }
        return acc;
    }
    
    var newData = data.map(function(x) {
    
        return x.items.map(function(xx) {
            return xx.items.map(function(xxx) {
                return [item(x), item(xx), item(xxx)];
            }).reduce(flatten, []);
    
    
        }).reduce(flatten, [])
    
    
    
    }).reduce(flatten, []).reduce(onlyUnique, []);;
    
    console.log(JSON.stringify(newData, null, 2))
    

提交回复
热议问题