javascript优化多个reduce和map从嵌套对象中提取数据

时间:2018-03-19 10:48:36

标签: javascript arrays ecmascript-6 mapreduce

我使用两个reduce es和map从嵌套对象数组中提取一些数据,这个数据正在运行,但它有点难看。如何优化?



function extractSchools(schools) {
  let schoolData = [];

  if (schools) {
    schoolData = schools.reduce(function(parentdata, chlrn) {
      let childrenlist = chlrn.children;
      let childrendata = [];

      if (childrenlist) {
        childrendata = childrenlist.reduce(function(addrsslist, school) {
          return addrsslist.concat(school.address.map(i => i.school));
        }, []);
      }

      return parentdata.concat(chlrn.parent, childrendata);
    }, []);
  }

  return {
    schoolData
  };
}

const schools = [{
    "parent": "Thomas Jefferson",
    "children": [{
        "address": [{
          "school": "School A"
        }]
      },
      {
        "address": [{
          "school": "School B"
        }]
      }
    ]
  },
  {
    "parent": "Jack Chan",
    "children": [{
      "address": [{
        "school": "School C"
      }]
    }]
  }
];


console.log(extractSchools(schools));




如何优化此功能以获得相同的结果?使用一个reduce代替两个......或其他一些最佳方式。

2 个答案:

答案 0 :(得分:1)

您可以移除if (childrenlist) {并使用预过滤器。

function extractSchools(schools) {
  let schoolData = [];

  if (schools) {
    schoolData = schools
      .filter(data => data.children)
      .reduce((parentdata, chlrn) => {
        const childrendata = chlrn.children.reduce(
          (addrsslist, school) =>
            addrsslist.concat(school.address.map(i => i.school)),
          []
        );
        return parentdata.concat(chlrn.parent, childrendata);
      }, []);
  }

  return { schoolData };
}

const schools = [
  {
    parent: "Thomas Jefferson",
    children: [
      {
        address: [
          {
            school: "School A"
          }
        ]
      },
      {
        address: [
          {
            school: "School B"
          }
        ]
      }
    ]
  },
  {
    parent: "Jack Chan",
    children: [
      {
        address: [
          {
            school: "School C"
          }
        ]
      }
    ]
  }
];

console.log(extractSchools(schools));

答案 1 :(得分:1)

试试这个,结果与你期望的结果没什么不同,但这将是一个更通用的方式,你将获得有关学校的地址。

schools.map(p => {
    return {[p.parent]: p.children.map(c => c.address.map(add => add.school))}
})


[
  {
    "Thomas Jefferson": [
      [
        "School A"
      ],
      [
        "School B"
      ]
    ]
  },
  {
    "Jack Chan": [
      [
        "School C"
      ]
    ]
  }
]