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

React中如何将多输入框的对象数组转为逗号分隔字符串存入数据库

提取React状态中对象数组的fullName字段为逗号分隔字符串

你遇到的问题是因为直接对对象数组调用toString()时,JavaScript会把每个对象转为[object Object],所以输出不是你需要的内容。要提取所有fullName并拼成逗号分隔的字符串,用map+join就能解决:

核心代码逻辑

// 提取所有fullName,过滤空值后拼接成逗号分隔字符串
const fullNamesString = inputFields
  .map(item => item.fullName)
  .filter(Boolean) // 可选:过滤掉空的fullName,避免出现连续逗号
  .join(',');

修改后的完整代码示例

import { useState } from "react";
function AddRemoveInputField() {
  const [inputFields, setInputFields] = useState([
    {
      fullName: "",
    },
  ]);

  const addInputField = () => {
    setInputFields([
      ...inputFields,
      {
        fullName: "",
      },
    ]);
  };

  const removeInputFields = (index) => {
    const rows = [...inputFields];
    rows.splice(index, 1);
    setInputFields(rows);
  };

  const handleChange = (index, evnt) => {
    const { name, value } = evnt.target;
    const list = [...inputFields];
    list[index][name] = value;
    setInputFields(list);    
  };

  // 生成要存入数据库的字符串
  const fullNamesString = inputFields
    .map(item => item.fullName)
    .filter(Boolean)
    .join(',');

  console.log('要存入数据库的字符串:', fullNamesString);
  console.log('原数组:', inputFields);
 
  // 这里可以添加提交到数据库的逻辑,比如调用API时传入fullNamesString
}

说明

  1. map(item => item.fullName):遍历对象数组,把每个对象的fullName字段提取出来,得到一个纯字符串数组
  2. filter(Boolean):可选步骤,去掉数组中的空字符串(比如用户没填写的输入框),避免最终字符串出现,,这种无效内容
  3. join(','):把字符串数组用逗号连接成一个完整的字符串,直接存入数据库即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 09:35:15