【问题标题】:Converting array objects into json in react在反应中将数组对象转换为json
【发布时间】:2020-12-05 14:44:46
【问题描述】:

我有两个数组对象,需要在 json 对象中使用这两个数组。 react中如何实现?

let qn = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
let ans= [false, false, false, false, false, false, false, false, false, false];

出于插入数据库的目的,我需要像这样转换上面的两个数组。

options: [{qn: "1", ans: false}, {qn: "2", ans: false}, ....., {qn: "10", ans: false}]

【问题讨论】:

    标签: arrays json reactjs object


    【解决方案1】:

    您可以将map 与索引一起使用

    let qn = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
    let ans = [false, true, false, false, false, false, false, false, false, true]
    
    const res = {
      options: qn.map((q, index) => ({
        qn: q,
        ans: ans[index],
      })),
    }
    
    console.log(res)

    【讨论】:

    • 让 text = this.props.data.matrix.options;让用户回答 = []; for (let j = 0; j ({ text: t, userAnswer: userAnswer[index], })); console.log(options);
    • 您对这个问题的评论对我帮助很大,但我需要更多信息。
    • 我得到了选项:[{text: {text: "1"}, userAnswer: false}]....而不是这种格式,我需要这样:选项:[{text : "1", userAnswer: false}].
    • @SureshKumarPasupulati 你应该使用text: t.text 而不是text: t,完整:const options = this.props.data.matrix.options.map((t, index) => ({ text: t.text, userAnswer: userAnswer[index], }))
    • 很高兴您立即帮助了我....非常感谢! @hgb123
    猜你喜欢
    • 2023-02-10
    • 2012-07-21
    • 2020-10-02
    • 1970-01-01
    • 1970-01-01
    • 2018-09-12
    • 2015-10-30
    相关资源
    最近更新 更多