首页 > 解决方案 > 使用占位符信息正确构造数组,直到填充所选对象

问题描述

这是一个令人困惑的问题,我不知道如何正确地谷歌它,所以如果它已经得到回答,我深表歉意。我正在尝试创建一个构建您自己的产品类型的应用程序,它允许用户选择他们成品的每个部分,但我不确定我应该如何构建我的数据以正确存储用户的选择。现在我有一个结构如下的数组:

selectedParts: [
    {
      component: "color",
      selected: null,
    },
    {
      component: "wheels",
      selected: null,
    },
    {
      component: "size",
      selected: null,
    },
    (...etc.)
  ],

当他们选择他们的选择时,它会用零件对象填充适当对象的“选定”字段。这是我为填充该数组而运行的函数(我正在使用 React,并且该数组处于我的状态):

onSelectPart = part => {
    let selectionIndex = this.state.selectedParts.findIndex(
      i => i.component === this.state.partCategory
    )
    let cloneArray = [...this.state.selectedParts]

    cloneArray[selectionIndex].selected = part

    this.setState({
      selectedParts: cloneArray,
    })
}

通过找到他们当前选择的类别的索引,然后克隆数组并使用索引将部分添加到克隆的数组中,然后将新数组推送到状态,将零件放入数组中。

这对我来说是错误的,而且比它应该的更复杂。我想尝试将它们全部保存在一个数组中,以便我可以在最后映射并轻松打印出完整的订单摘要,但如果这是错误的方法,那么推荐的方法是什么?将对象嵌套在“订单”对象中是否是一种好方法,而不是使用数组?

标签: javascriptreactjs

解决方案


如果您可以选择使用哪种数据结构,那么创建selectedParts对象对您来说会更容易,性能也会更好,因为您可以在恒定时间内访问对象(您不必每次都循环访问)。属性是对象component,值是part对象:

selectedParts: {
  color: null,
  wheels: null,
  size: null,
  ...
}

然后要更新它,您仍然需要复制和更新,但要容易得多:

const onSelectPart = part => {
  const selectedParts = {...this.state.selectedParts}; 
  selectedParts[this.state.partCategory] = part; // using "computed names"
  this.setState({ selectedParts });
}

最后,您可以打印遍历selectedParts条目的顺序:

const printOrderSummary = selectedParts => {
  // Note: [category, part] is just key, value of your object
  for (let [category, part] of Object.entries(selectedParts)) {
    if (part === null) part = 'Not selected'; // or skip the category, etc.

    // this would be whatever you're currently doing to map your order
    console.log(`${category}: ${part}`);
  }
}

推荐阅读