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",
},{...}
{...}
{...}
...
...]
现在借助下面的代码,我将转换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",
},
{....},
{....},
{....},
....
....]
解决方案
您可以按如下方式更新
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)
推荐阅读
- java - Jackson XML 序列化 - 删除字段标签
- r - R中的read.xlsx有问题
- php - Laravel Voyager:调用未定义的方法 TCG\Voyager\ getCoordinates()
- css - 我该如何解决这些错位?
- dataweave - DW 2.0 中的多态性
- oracle - PLS-00103:在预期以下情况之一时遇到符号“文件结尾”:开始函数杂注过程子类型类型
- javascript - 如何映射此对象数组以从每个产品项目中获取新的地理数组?
- java - Java、Firebase、请求通知权限
- android - Firebase 数据库免受 apk 反编译和使用的影响
- reactjs - 只显示点击卡片的内容