cdn34
cdn34

Reputation: 107

Nested arrays in normalizr schema

I need to normalize this data so that I have both an array of lists and another of todos.

const data = [ 
  { 
    _id: '1', 
    title: 'List1', 
    todos: [
      {
         _id: "11", 
         text: "Test1"
      }
    ] 
  },
  { 
    _id: '2', 
    title: 'List2', 
    todos: [
      {
         _id: "22", 
         text: "Test2"
      }
    ] 
  } 
];

Here's what I got:

const todo = new schema.Entity('todos',{},{ idAttribute: '_id'});
const list = new schema.Entity('lists',{todos:todo},{idAttribute: '_id'});
const normalizedData = normalize(data, list);
console.log(normalizedData);

I've been trying their examples but none of them seem to work for this data.

Any help would be appreciated.

Upvotes: 4

Views: 2199

Answers (1)

Paul Armstrong
Paul Armstrong

Reputation: 7156

You need to tell the schema that todos is an array of todo and that your input data is an array:

const list = new schema.Entity('lists', { todos: [ todo ]}, { idAttribute: '_id' });
const normalizedData = normalize(data, [ list ]);

or

const list = new schema.Entity('lists', { todos: new schema.Array(todo) } , { idAttribute: '_id' });
const normalizedData = normalize(data, new schema.Array(list));

Upvotes: 9

Related Questions