JS 数组转Object和Map
一、结论:
1、JavaScript 对象的属性顺序规则是:对象属性如果是“数字型键”,在遍历时会按照 数值升序 排列。
2、需要键值对 + 保持顺序,建议用 Map
二、代码
<ProFormSelectdisabled={!pointReason}allowClear={false}label={formatMessage({ id: 'apple' })}name="amount"rules={[{ required: true }]}valueEnum={amountValueEnum}/>
valueEnum 值 支持 object 和Map,Map 是支持其他基础类型作为 key
const arr = [3000, 2000, 1000];
1、转成Map类型
const map = new Map(arr.map((item) => [item, item.toString()]));console.log(map);
输出: {3000 => '3000', 2000 => '2000', 1000 => '1000'}2、转成objectconst amountValueEnum = arr.reduce((acc, val, index) => {acc[val.toString()] = val.toString();return acc;},{} as Record<string, string>);
输出:{1000: '1000', 2000: '2000', 3000: '3000'}
3、Map 转object
const amountValueEnum = Object.fromEntries(priceData?.amountList?.map((item, index) => [item.toString(), // key 必须是 stringpriceData?.addTemporaryQuota && index === 0? item.toString() + '⬆': item.toString(), // 展示用]) || []输出:{1600000: '1600000', 1900000: '1900000', 2200000: '2200000', 2600000: '2600000', 3000000: '3000000', 3500000: '3500000', 4000000: '4000000'}