Deep Flatten JavaScript Object Recursively

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

Data:

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


        
14条回答
  •  粉色の甜心
    2021-02-18 21:14

    Here is my version of the recursive flattenItems function. Note that I have removed the items property at all levels in the final result.

    function flattenItems(data) {
        // flat is the array that we will return by the end
        var flat = [];
        data.forEach(function(item) {
            // get child properties only
            var flatItem = {};
            Object.keys(item).forEach(function(key) {
                if(item[key] && item.hasOwnProperty(key) && !Array.isArray(item[key])) {
                    flatItem[key] = item[key];
                }
                // recursive flattern on subitems
                // add recursive call results to the 
                // current stack version of "flat", by merging arrays
                else if(Array.isArray(item[key])) {
                    Array.prototype.push.apply(flat, flattenItems(item[key]));
                }
            });
            flat.push(flatItem);
        });
        // sort by level before returning
        return flat.sort(function(i1, i2) {
            return parseInt(i1.level) - parseInt(i2.level);
        });
      }
    

    Here is a fiddle using your sample data, check the console.

提交回复
热议问题