首页 > 解决方案 > 如何将普通数组转换为嵌套在父对象中的嵌套对象

问题描述

我正在尝试将普通数组转换为带有附加参数的对象

可以说,我有一个对象

var obj = [{
    index: 1,
    question: "If a carrier wave of 1000 kHz is used to carry the signal, the length of transmitting antenna will be equal to _____ ?",
    choices_list: ["300 m", "30 m", "3 m", "0.3 m"],
    answer: "300 m",
    explanation: "h =  c/v = 3 × 10^8/10^6 = 300 m",
},{...}
{...}
{...}
...
...]

现在借助下面的代码,我将转换choices_list为对象

res_quiz_data.forEach(key => {
    console.log(key.choices_list);

    const map1 = key.choices_list.map(x => {
        return { selected: false, choice: x }
    });
    console.log(map1);
})

输出

JS: [300 m, 30 m, 3 m, 0.3 m]
JS: [{
JS:   "selected": false,
JS:   "choice": "300 m"
JS: }, {
JS:   "selected": false,
JS:   "choice": "30 m"
JS: }, {
JS:   "selected": false,
JS:   "choice": "3 m"
JS: }, {
JS:   "selected": false,
JS:   "choice": "0.3 m"
JS: }]

现在我需要修改主要的 Json 对象

预期产出

var obj = [{
    index: 1,
    question: "If a carrier wave of 1000 kHz is used to carry the signal, the length of transmitting antenna will be equal to _____ ?",
    choices_list: [{
       "selected": false,
       "choice": "300 m"
     }, {
       "selected": false,
       "choice": "30 m"
     }, {
       "selected": false,
       "choice": "3 m"
     }, {
       "selected": false,
       "choice": "0.3 m"
     }],
    answer: "300 m",
    explanation: "h =  c/v = 3 × 10^8/10^6 = 300 m",
    },
{....},
{....},
{....},
....
....]

标签: javascript

解决方案


您可以按如下方式更新

var obj = [{
    index: 1,
    question: "If a carrier wave of 1000 kHz is used to carry the signal, the length of transmitting antenna will be equal to _____ ?",
    choices_list: ["300 m", "30 m", "3 m", "0.3 m"],
    answer: "300 m",
    explanation: "h =  c/v = 3 × 10^8/10^6 = 300 m",
}]

var output = obj.map(o => {
  o.choices_list = o.choices_list.map(choice => ({selected: false,
  choice}))
  return o
})


console.log(output)

如果要在同一个对象上更新,可以执行以下操作

var _obj = [{
    index: 1,
    question: "If a carrier wave of 1000 kHz is used to carry the signal, the length of transmitting antenna will be equal to _____ ?",
    choices_list: ["300 m", "30 m", "3 m", "0.3 m"],
    answer: "300 m",
    explanation: "h =  c/v = 3 × 10^8/10^6 = 300 m",
}]

_obj.forEach(o => {
  o.choices_list = o.choices_list.map(choice => ({selected: false,
  choice}))
  return o
})


console.log(_obj)


推荐阅读