Deep Flatten JavaScript Object Recursively

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

Data:

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


        
14条回答
  •  深忆病人
    2021-02-18 21:13

    With a bit of ES6 flavor

    function flatten(xs) {
      return xs.reduce((acc, x) => {
        acc = acc.concat(x);
        if (x.items) {
          acc = acc.concat(flatten(x.items));
          x.items = [];
        }
        return acc;
      }, []);
    }
    

提交回复
热议问题