Deep Flatten JavaScript Object Recursively

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

Data:

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


        
14条回答
  •  故里飘歌
    2021-02-18 21:10

    Modified Роман Парадеев answer to make it somewhat more dynamic.

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

    Now items is not hardcoded, and you can use it flatten(data, x => x.items).

提交回复
热议问题