Search code examples
javascriptimmutable.js

Keep Object as Object after filtering


That is my datastructure

const data = Immutable.fromJS({
        1: {
            foo: 'bar'
            ...
        },
        2: {
            foo: 'foo'
            ...
        },
        3: {
            foo: 'foobar'
            ...
        },
    },
});

I want to filter the data and I need my filteredData to be of exactly the same type - Immutable Object. When I run

const filtered = data.get('data').valueSeq().filter(obj => {
    ...
    return obj;
});

I get this [{}, {}, {}, ...].

I need it to be like this (as the input data) {1: {...}, 2: {...}, 3: {...}}. What is the correct filter function for this so that the return type is already a Map and not an Array. Or is there nothing like this.


Solution

  • After filtering your object is still an ImmutableObject (see example)

    const data = Immutable.fromJS({
        data: {
            1: {
                foo: 'bar'
            },
            2: {
                foo: 'foo'
            },
            3: {
                foo: 'foobar'
            },
        },
        kittens: {}
    });
    
    const res = data.get('data').filter(obj=>obj.get('foo') === 'bar');
    console.log(res);
    
    //still immutable object
    console.log(res.get('1'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.min.js"></script>