首页  编辑  

列表转换 reduce

Tags: /Node & JS/   Date Created:
假设有如下 smpList 数据结构,按 scd-mcd-pcd 作为 key 组织数据,希望转换为 按 scd-pcd-mcd 作为 key 组织数据,示例代码如下:
const smpList = [
	{
		"scd": "s001",
		"mcd": "m001",
		"list": [
			{ "pcd": "NC"},
			{ "pcd": "PT"},
			{ "pcd": "OPT"},
		]
	},
	{
		"scd": "s001",
		"mcd": "m002",
		"list": [
			{ "pcd": "NC"},
			{ "pcd": "PT"},
			{ "pcd": "OPT"},
		]
	},
	{
		"scd": "s002",
		"mcd": "m001",
		"list": [
			{ "pcd": "DT"},
			{ "pcd": "OPT"},
		]
	},
]
const spmList = smpList.reduce((result, currentItem) => {
      currentItem.list.forEach(one=> {
        const existingItem = result.find(item => item.scd === currentItem.scd && item.pcd === one.pcd);
        if (existingItem) {
          existingItem.list.push({ "mcd": currentItem.mcd});
        } else {
          result.push({
            "scd": currentItem.scd,
            "pcd": one.pcd,
            "list": [{ "mcd": currentItem.mcd}]
          });
        }
      })
      return result;
    }, []);
console.log("转换后:")
console.log(spmList)
返回的 spmList 就是 Array<SPM>了:
[
	{
		"scd": "s001",
		"pcd": "NC",
		"list": [
			{ "mcd": "m001"},
			{ "mcd": "m002"},
		]
	},
	{
		"scd": "s001",
		"pcd": "PT",
		"list": [
			{ "mcd": "m001"},
			{ "mcd": "m002"},
		]
	},
	{
		"scd": "s001",
		"pcd": "OPT",
		"list": [
			{ "mcd": "m001"},
			{ "mcd": "m002"},
		]
	},
	{
		"scd": "s002",
		"pcd": "DT",
		"list": [
			{ "mcd": "m001"},
		]
	},
	{
		"scd": "s002",
		"pcd": "OPT",
		"list": [
			{ "mcd": "m001"},
		]
	},
]