You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React的mapStateToProps中将嵌套对象转换为扁平对象?

嘿,我懂你想要在mapStateToProps里用更简洁的方式搞定这个对象结构转换,不想写额外的辅助变量或者单独的函数对吧?

你的思路方向是对的,但map方法确实会返回数组,而我们最终需要的是一个对象。这里有两个原生JS的方案,完全可以直接写在mapStateToProps里,不用额外代码:

方案1:用Object.fromEntries(推荐,语法更简洁)

Object.fromEntries可以把键值对数组直接转换成对象,正好适配我们用map生成的结果:

const mapStateToProps = state => {
  return {
    ingredients: Object.fromEntries(
      Object.keys(state.burger.ingredients).map(ingredientKey => [
        ingredientKey,
        state.burger.ingredients[ingredientKey].amount
      ])
    ),
    totalPrice: state.burger.totalPrice
  };
};

这里map会生成类似[['salad', 3], ['cheese', 2]]的键值对数组,Object.fromEntries直接把它转成你想要的扁平对象{salad: 3, cheese: 2}。

方案2:用Array.reduce(兼容更早的JS环境)

如果需要考虑旧浏览器兼容性,reduce也是个很好的选择,逻辑和你之前的for循环一致,但可以内联写:

const mapStateToProps = state => {
  return {
    ingredients: Object.keys(state.burger.ingredients).reduce((flatObj, key) => {
      flatObj[key] = state.burger.ingredients[key].amount;
      return flatObj;
    }, {}), // 初始值是空对象
    totalPrice: state.burger.totalPrice
  };
};

reduce从空对象开始遍历每个食材键,把对应的amount赋值给新对象的对应键,最后返回这个扁平对象。

你之前用map得到的是[{salad:3}, {cheese:2}]这样的对象数组,虽然也可以用Object.assign(...array)或者展开运算符合并,但上面两个方案会更直接高效哦。

内容的提问来源于stack exchange,提问作者source144

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:25:40