Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 700
cdn34 Avatar asked Jan 05 '23 14:01

cdn34


1 Answers

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));
like image 82
Paul Armstrong Avatar answered Jan 14 '23 18:01

Paul Armstrong