遍历对象数组以更新对象值并附加其他对象

时间:2019-08-09 22:47:25

标签: javascript arrays javascript-objects

我有一个包含对象的fields数组,我正在尝试循环该数组:

fields: [
    {
        name: "seasonId",
        type: "select",
        label: "Season ID",
        placeholder: "Select a season id...",
        icon: "id",
        value: "",
        errors: "",
        required: true,
        disabled: true,
        selectOptions: [],
    },
    {
        name: "callTime",
        type: "time",
        label: "Scheduling Call Times",
        placeholder: "Select a time...",
        value: "",
        errors: "",
        required: true,
        disabled: true,
    },
];

要更新其值并附加其他对象:

传入值

"fieldValues": {
  "callTimes": [
    "5:45 pm",
    "6:15 pm",
    "6:30 pm",
    "7:00 pm"
  ],
  "selectedSeasonId": "20192020",
  "seasonIds": [
    "20192020",
    "20202021",
    "20212022",
  ]
}

更新字段功能

const updateField = (currentField, fieldValues) => {
  switch(currentField.name) {
    case "seasonId":
      return {
        ...currentField,
        selectOptions: fieldValues.seasonIds,
        value: fieldValues.selectedSeasonId,
        disabled: false
      };
    case "callTime":
      const callTimes = fieldValues.callTimes.map((value, key) => ({
        ...currentField,
        name: key <= 0 ? "callTime" : `callTime-${Date.now()}`,
        label: key <= 0 ? "Scheduling Call Times" : "",
        value,
        required: key <= 0,
        disabled: false,
      }));

      return { 
        ...callTimes 
      };
  }
}

然后像这样调用上面的函数:

const updatedFields = fields.map(field => updateField(field, event));

但是,我没有得到想要的结果。

实际输出

[
  '0': {
    disabled: false
    errors: ""
    icon: "id"
    label: "Season ID"
    name: "seasonId"
    placeholder: "Select a season id..."
    required: true
    selectOptions: ["20192020", "20202021", "20212022"]
    type: "select"
    value: "20192020"
  },
  '1': {
         '0': {  
           disabled: false
           errors: ""
           label: "Scheduling Call Times"
           name: "callTime"
           placeholder: "Select a call time..."
           required: true
           style: {width: "100%"}
           type: "time"
           value: "5:45 pm"
         },
         '1': {
           disabled: false
           errors: ""
           label: ""
           name: "callTime-1565388886669"
           placeholder: "Select a call time..."
           required: false
           style: {width: "100%"}
           type: "time"
           value: "6:15 pm"
         },
         '3': { ... },
         '4': { ... }
      }
];

预期输出

[
  '0': {
    disabled: false
    errors: ""
    icon: "id"
    label: "Season ID"
    name: "seasonId"
    placeholder: "Select a season id..."
    required: true
    selectOptions: ["20192020", "20202021", "20212022"]
    type: "select"
    value: "20192020"
  },
  '1': {
    disabled: false
    errors: ""
    label: "Scheduling Call Times"
    name: "callTime"
    placeholder: "Select a call time..."
    required: true
    style: {width: "100%"}
    type: "time"
    value: "5:45 pm"
  },
  '2': {
     disabled: false
     errors: ""
     label: ""
     name: "callTime-1565388886669"
     placeholder: "Select a call time..."
     required: false
     style: {width: "100%"}
     type: "time"
     value: "6:15 pm"
  },
  '3': { ... },
  '4': { ... }
];

关于如何更新值并将其他对象附加到我的字段数组的任何想法? callTimes对象中的field字符串值数组是动态的(可以包含1个或多个字符串),因此我不能对任何东西进行硬编码。

const fields = [
    {
        name: "seasonId",
        type: "select",
        label: "Season ID",
        placeholder: "Select a season id...",
        icon: "id",
        value: "",
        errors: "",
        required: true,
        disabled: true,
        selectOptions: [],
    },
    {
        name: "callTime",
        type: "time",
        label: "Scheduling Call Times",
        placeholder: "Select a time...",
        value: "",
        errors: "",
        required: true,
        disabled: true,
    },
];

const fieldValues = {
  "callTimes": [
    "5:45 pm",
    "6:15 pm",
    "6:30 pm",
    "7:00 pm"
  ],
  "selectedSeasonId": "20192020",
  "seasonIds": [
    "20192020",
    "20202021",
    "20212022",
  ]
};


const updateField = (currentField, event) => {
  switch(currentField.name) {
    case "seasonId":
      return {
        ...currentField,
        selectOptions: fieldValues.seasonIds,
        value: fieldValues.selectedSeasonId,
        disabled: false
      };
    case "callTime":
      const callTimes = fieldValues.callTimes.map((value, key) => ({
        ...currentField,
        name: key <= 0 ? "callTime" : `callTime-${Date.now()}`,
        label: key <= 0 ? "Scheduling Call Times" : "",
        value,
        required: key <= 0,
        disabled: false,
      }));

      return { 
        ...callTimes 
      };
  }
};

const updatedFields = fields.map(field => updateField(field, event));

console.log(updatedFields);

1 个答案:

答案 0 :(得分:1)

使用reduce而不是map,我相信我得到了正确的输出:

const updateField = (result, currentField) => {
  switch (currentField.name) {
    case 'seasonId':
      return [
        ...result,
        {
          ...currentField,
          selectOptions: fieldValues.seasonIds,
          value: fieldValues.selectedSeasonId,
          disabled: false
        }
      ]
    case 'callTime':
      const callTimes = fieldValues.callTimes.map(...);
      return [
        ...result,
        ...callTimes
      ]
  }
}
const updatedFields = fields.reduce(updateField, [])

由于您的callTime案例返回了数组中的多个对象,因此map在这种情况下无法正常工作,因为您需要将这些对象分别推入/添加到“最终”数组中,因此此return

case 'callTime':
  const callTimes = fieldValues.callTimes.map(...);
  return [
    ...result,
    ...callTimes
  ]

另外,您的callTimes出来是一个数组,您试图将其项散布到一个对象中:

case "callTime":
  const callTimes = fieldValues.callTimes.map(...); // array
  return { 
    ...callTimes 
  };

这就是为什么您得到意外/奇怪的结果的原因。

这是一个带有修复程序的演示:


由于您在注释中询问了如何将fieldValues传递给reducer函数,因为它们是从另一个文件导入的,因此您可以执行以下操作:

const updateField = (result, currentField, fieldValues) => {...}

const updatedFields = fields.reduce(
  (result, field) => updateField(result, field, fieldValues), 
  []
)

其他所有内容保持不变。

这是另一个演示: