【问题标题】:Normalize Deep nested data规范化深层嵌套数据
【发布时间】:2021-10-04 15:56:43
【问题描述】:

我需要用深度嵌套的结构规范化 api 响应数据。 我正在使用这个https://github.com/paularmstrong/normalizr 来规范我的数据。

我有一个输入数据

const data = [{
  id: 'component1,
  name: 'component one,
  properties:[{
    name: 'text',
    color: 'red'
  }]
},
{
  id: 'component2,
  name: 'component two',
  properties:[{
    name: 'text',
    color: 'yellow'
  },{
    name: 'button',
    color: 'blue'
  }]
}]

标准化后的预期输出

    { 
      entities: {
        component1: {
           id: 'component1,
           name: 'component one,
           properties: {
             entities: {
               text: {
                  name: 'text',
                  color: 'red'
               }
             },
             results: ['text']
           }
        },
        component2: {
           id: 'component2,
           name: 'component two,
           properties: {
             entities: {
               text: {
                  name: 'text',
                  color: 'yellow'
               },
               button: {
                 name: 'button',
                 color: 'blue'
               }
             },
             results: ['text', 'button']
           }
        }
      },
      results: ['component1', 'component2']
    }

请帮忙

【问题讨论】:

    标签: javascript arrays json normalization normalizr


    【解决方案1】:

    这是我的方法,使用forEach() 迭代所有数据,以便以您想要的格式重新排列:

    const data = [{id: 'component1',name: 'component one',properties:[{name: 'text',color: 'red'}]},{id: 'component2',name: 'component two',properties:[{name: 'text',color: 'yellow'},{name: 'button',color: 'blue'}]}];
    
    let result = {entities: {}, result: []};
    data.forEach(c => {
      result.result.push(c.id);
      result.entities[c.id] = {
        id: c.id,
        name: c.name,
        properties: {
          entities: Object.fromEntries(c.properties.map(p => [p.name, p])),
          results: c.properties.map(p => p.name)
        }
      };
    });
    
    console.log(result);

    【讨论】:

      猜你喜欢
      • 2021-05-22
      • 2020-11-09
      • 2019-09-04
      • 2018-05-23
      • 1970-01-01
      • 2021-12-12
      • 2020-03-05
      • 2016-06-20
      • 2019-12-22
      相关资源
      最近更新 更多