How to add list to list in Immutable.js?

Viewed 3186

What is the best way to add List to List in Immutable.js?

concat method is working, but another way is not working.

const a = fromJS([  
                {
                    comment: 'aaaa',
                    who: 'a1',
                    buttonInfo: ['a', 'b', 'c'],
                },
               {
                    comment: 'bb',
                    who: 'a2',
                    buttonInfo: ['a', 'b', 'c'],
                },
            ]);

const b = fromJS([  
                {
                    comment: 'ccc',
                    who: 'c1',
                    buttonInfo: ['a', 'b'],
                },
               {
                    comment: 'ddd',
                    who: 'd2',
                    buttonInfo: ['a''],
                },
            ]);

This is working:

a.concat(b)

But this is not working:

[...a ,...b]

// or

b.map(v => {
  a.push(v);
})
3 Answers

you can use concat method as it said in doc:

const list1 = List([ 1, 2, 3 ]);
const list2 = List([ 4, 5, 6 ]);
const array = [ 7, 8, 9 ];
const list3 = list1.concat(list2, array);
// List [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

An ImmutableJS list has a method named concat whose behavior is the same as a normal javascript array. However, you cannot use spread syntax for an Immutable array.

Also the syntax for push is different from the normal array, push like concat with Immutable List returns a new list, your map method will look like

b.map(v => {
   a = a.push(v);
})

P.S. Using the above method though will mutate your array a. You must create a new List and then push both the array contents into it if you want to use push. However concat is the best way for your case

For add List to List in Immutable.js, you can use merge method.

Example:

const a = fromJS(
  [  
    {
      comment: 'aaaa',
      who: 'a1',
      buttonInfo: ['a', 'b', 'c'],
    },
    {
      comment: 'bb',
      who: 'a2',
      buttonInfo: ['a', 'b', 'c'],
    },
  ]
);

const b = fromJS(
  [  
    {
      comment: 'ccc',
      who: 'c1',
      buttonInfo: ['a', 'b'],
    },
    {
      comment: 'ddd',
      who: 'd2',
      buttonInfo: ['a''],
    },
  ]
);


a.merge(b);
Related