Normalizr:规范化深层嵌套项

Posted

技术标签:

【中文标题】Normalizr:规范化深层嵌套项【英文标题】:Normalizr: normalize deep nested items 【发布时间】:2021-05-22 18:56:54 【问题描述】:

我有一个这样的数据数组

[
  
    "id": "root_01",
    "parents": [
      
        "id": "parent_1",
        "childrens": [
          
            "id": "child_01",
            "name": "ABC",
            "group": "group_a"
          ,
          
            "id": "child_02",
            "name": "BBC",
            "group": "group_b"
          
        ]
      ,
      
        "id": "parent_2",
        "childrens": [
          
            "id": "child_03",
            "name": "CCD",
            "group": "group_a"
          ,
          
            "id": "child_04",
            "name": "EEF",
            "group": "group_c"
          
        ]
      
    ]
  ,
   // same as previous
]

我正在尝试删除所有父母数据并仅捕获并合并像这样的子项目:

[
  
    "id": "child_01",
    "name": "ABC",
    "group": "group_a"
  ,
  
    "id": "child_02",
    "name": "BBC",
    "group": "group_b"
  ,
  
    "id": "child_03",
    "name": "CCD",
    "group": "group_a"
  ,
  
    "id": "child_04",
    "name": "EEF",
    "group": "group_c"
  
]

但在阅读normalizr 文档后,我有点困惑,因为我找不到这种示例,所以有人可以建议我是否可以使用 normalizr 或任何更好的想法?

谢谢

【问题讨论】:

这能回答你的问题吗? Find by key deep in a nested array 【参考方案1】:

Recusrion 是你需要的:

const arr = [  "id": "root_01", "parents": [  "id": "parent_1", "childrens": [  "id": "child_01", "name": "ABC", "group": "group_a" ,  "id": "child_02", "name": "BBC", "group": "group_b"  ] ,  "id": "parent_2", "childrens": [  "id": "child_03", "name": "CCD", "group": "group_a" ,  "id": "child_04", "name": "EEF", "group": "group_c"  ]  ] ];

const flatten = arr => arr.flatMap(o=>o.parents ? flatten(o.parents) : o.childrens ? flatten(o.childrens) : o);

console.log(flatten(arr));

【讨论】:

以上是关于Normalizr:规范化深层嵌套项的主要内容,如果未能解决你的问题,请参考以下文章

Normalizr 规范化嵌套数据

为啥非规范化不返回嵌套对象?

如何使用 Normalizr 定义递归模型的模式

如何使用 normalizr 规范化来自 JSON 的数据?

如何使用“normalizr”规范化这个简单的 API 响应?

redux 中 normalizr 后的非规范化实体