从不可变映射中获取多个键的最佳方法?
Best approach to get multiple keys from an immutable map?
从不可变映射中获取多个值的最佳方法是什么?
const example = new Map({
id: 1,
first: 'John',
last: 'Smith',
age: '99',
gender: 'M',
children: new List([7,8,10]),
});
使用toJS()
是一种方法:
const {
first,
last,
age,
gender
} = example.toJS();
但如果我拉入 children 它将不再是一个不可变的列表。
使用get()
:
const first = example.get('first');
const last = example.get('last');
...
这保持了 children 的类型,但看起来像是额外的循环和击键。
有什么想法吗?
我知道这可能是一个自以为是的问题,但我正在寻找有价值的东西,请包括统计数据(击键、循环)以支持您的回答。
就我个人而言,我可能会坚持使用 .get()
s,但是如果你想使用解构,你可以尝试 .toJSON()
method. It's like .toJS()
but it only does a shallow conversion to either an object or an array. You could also use .toObject()
or .toArray()
如果你知道你想要什么类型把它变成(如果你要解构它,你必须这样做)。
const m = Immutable.fromJS({
a: {a2: 'a3'},
b: [1, 2, {f: 'f'}],
});
const { a, b } = m.toJSON();
console.assert(Immutable.isImmutable(a) && Immutable.isImmutable(b));
console.log('a =', a);
console.log('b =', b)
const [ c, d, e ] = b.toArray();
console.assert(c == 1 && d == 2 && Immutable.isImmutable(e));
const { f } = e.toObject();
console.assert(f === 'f');
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/4.0.0-rc.9/immutable.js"></script>
我做了一个 jsperf 因为你提到你想要统计数据。对于我在 MacBook Pro 上使用 Chrome 63,.get
大约是 .toJSON
的 3 倍
从不可变映射中获取多个值的最佳方法是什么?
const example = new Map({
id: 1,
first: 'John',
last: 'Smith',
age: '99',
gender: 'M',
children: new List([7,8,10]),
});
使用toJS()
是一种方法:
const {
first,
last,
age,
gender
} = example.toJS();
但如果我拉入 children 它将不再是一个不可变的列表。
使用get()
:
const first = example.get('first');
const last = example.get('last');
...
这保持了 children 的类型,但看起来像是额外的循环和击键。
有什么想法吗?
我知道这可能是一个自以为是的问题,但我正在寻找有价值的东西,请包括统计数据(击键、循环)以支持您的回答。
就我个人而言,我可能会坚持使用 .get()
s,但是如果你想使用解构,你可以尝试 .toJSON()
method. It's like .toJS()
but it only does a shallow conversion to either an object or an array. You could also use .toObject()
or .toArray()
如果你知道你想要什么类型把它变成(如果你要解构它,你必须这样做)。
const m = Immutable.fromJS({
a: {a2: 'a3'},
b: [1, 2, {f: 'f'}],
});
const { a, b } = m.toJSON();
console.assert(Immutable.isImmutable(a) && Immutable.isImmutable(b));
console.log('a =', a);
console.log('b =', b)
const [ c, d, e ] = b.toArray();
console.assert(c == 1 && d == 2 && Immutable.isImmutable(e));
const { f } = e.toObject();
console.assert(f === 'f');
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/4.0.0-rc.9/immutable.js"></script>
我做了一个 jsperf 因为你提到你想要统计数据。对于我在 MacBook Pro 上使用 Chrome 63,.get
大约是 .toJSON