Custom fromJS immutablejs issue

194 views Asked by At

I created a custom fromJS function so that when I convert objects over to Immutable objects then the result would only contain OrderedSets and Maps (instead of Lists and Maps).

This has worked perfectly fine except for in the following case where a key in the object is called "length". Any ideas how to fix the issue at hand?

var imm = require("immutable")

function fromJS(js) {
    return typeof js !== 'object' || js === null ? js :
        Array.isArray(js) ? 
            imm.Seq(js).map(fromJS).toOrderedSet() :
            imm.Seq(js).map(fromJS).toMap();
}

var output = fromJS({
    measurements: {
        length: 10,
        weight: 30
    }
}).toJS();

// output is :
{
    measurements: {
        0: undefined,
        1: undefined
        ....
        32: undefined
    }
}
1

There are 1 answers

0
Thaadikkaaran On BEST ANSWER

Got worked by changing the property length to mLength.

Here is the JSBin

ImmutableJS looks for length property to check whether the given value is array-like object or not.

Since your measurements object has a property length, it considers that this object is an array-like object and continues the Seq construction based on array-like type, here the problem starts.


To confirm this, here is the jsbin which outputs the Map with no.of time given in the length property of the measurements object.