Normalizr - 使用嵌套数组规范化对象数组

时间:2018-06-16 12:55:27

标签: normalizr

无法理解要使用的架构定义...

用于规范化此数据的架构定义:

[
      {
        manufacturer: "Foo",
        car: ["Foo-s1", "Foo-s2"]
      },
      {
        manufacturer: "Bar",
        car: ["Bar-c3", "Bar-c4"]
      }
]

这个形状:

entities: {
  manufacturers: {
    Foo: {
           id: Foo,
           cars: ["Foo-s1", "Foo-s2"]  
    },
    Bar: {
           id: Bar,
           cars: ["Bar-c3", "Bar-c4"]
    }
  },
  cars: {
     "Foo-s1": {
                 id: "Foo-s1",
     },
     //...etc
  }
};

1 个答案:

答案 0 :(得分:1)

您可以尝试这样的操作,但是您需要对原始输入执行一些数据转换。可能有更好的解决方案,这就是我想出的。

import { normalize, schema } from 'normalizr';

const originalData = [
  {
    id: "1",
    manufacturer: "Foo",
    car: ["Foo-s1", "Foo-s2"],
  },
  {
    id: "2",
    manufacturer: "Bar",
    car: ["Bar-c3", "Bar-c4"],
  }
];

const objectData = originalData.reduce((prev, curr) => {
  const updatedData = Object.entries(curr).reduce((obj, [k,v]) => {
    if(v.constructor === String && k !== 'id')
      return Object.assign({}, obj, {[k]: {'id': v}});
    if(v.constructor === Array) {
      const arrayData = v.reduce((vPrev, vCurr) => vPrev.concat({'id': vCurr}), []);
      return Object.assign({}, obj, {[k]: arrayData});
    }
    return Object.assign({}, obj, {[k]: v});
  }, {});
  return prev.concat(updatedData);
}, []);

const manufacturer = new schema.Entity('manufacturers');
const car = new schema.Entity('cars');
const manufactorData =  new schema.Entity('manufactorData', {
  manufacturer: manufacturer,
  car: [car]
});

const normalizedData = normalize(objectData, [manufactorData]);

console.log('Original Data: ', originalData);
console.log('ObjectData: ', objectData);
console.log('Normalized Data: ', normalizedData);

最终结果看起来像这样:

{
  "entities": {
    "manufacturers": {
      "Foo": {
        "id": "Foo"
      },
      "Bar": {
        "id": "Bar"
      }
    },
    "cars": {
      "Foo-s1": {
        "id": "Foo-s1"
      },
      "Foo-s2": {
        "id": "Foo-s2"
      },
      "Bar-c3": {
        "id": "Bar-c3"
      },
      "Bar-c4": {
        "id": "Bar-c4"
      }
    },
    "manufactorData": {
      "1": {
        "id": "1",
        "manufacturer": "Foo",
        "car": [
          "Foo-s1",
          "Foo-s2"
        ]
      },
      "2": {
        "id": "2",
        "manufacturer": "Bar",
        "car": [
          "Bar-c3",
          "Bar-c4"
        ]
      }
    }
  },
  "result": [
    "1",
    "2"
  ]
}