fromJS()未遵循规范化对象顺序:原因及保序方法咨询
fromJS() reorder my object keys, and how to preserve the original order? Great question! Let me break down what's happening here and how to fix it.
The Root Cause
When you use fromJS() to convert a plain JavaScript object to an Immutable structure, it defaults to creating a Map for plain objects. The key ordering you're seeing is actually due to how JavaScript handles object key enumeration, which Immutable.js follows strictly:
- JavaScript treats string keys that can be parsed as integers (like
"11") as "array-like indices" and sorts them in ascending numerical order first. - Regular string keys come next, in the order they were originally added to the object.
So if your action.payload.entities has a mix of numeric string keys and regular string keys, the numeric ones will jump to the front when converted to a default Map, which doesn't preserve the original insertion order of the plain object.
How to Preserve the Original Order
To keep the exact key order from your original normalized object, you need to tell fromJS() to use OrderedMap instead of the default Map. You can do this with a reviver function as the second argument to fromJS():
import { fromJS, OrderedMap } from 'immutable'; // Use a reviver to convert plain objects to OrderedMap instead of Map const normalizedMap = fromJS(action.payload.entities, (key, value) => { // Check if we're dealing with a plain object (not an array or primitive) const isPlainObject = typeof value === 'object' && value !== null && !Array.isArray(value); return isPlainObject ? OrderedMap(value) : value; }); console.log(normalizedMap);
What this does:
- The reviver function runs recursively for every value being converted by
fromJS(). - Whenever it encounters a plain object, it converts it to an
OrderedMap, which strictly preserves the insertion order of the original object's keys. - All other values (arrays, primitives) are handled normally by
fromJS().
This will ensure that your normalized structure keeps the exact key order you had in action.payload.entities, including that "11" key staying in its original position instead of jumping to the front.
内容的提问来源于stack exchange,提问作者UzumakiDev

