您好,我正在try 创建一个对象,该对象在相同的属性名称下包含一组数组值,

const quiz = [
    {question: 'Who is the main character of DBZ',
    options: ['Vegetta','Gohan','Goku']}
]

const newObj = {
    options: []
}
quiz.forEach((item)=>{
    item.options.forEach((item, index)=>{
        
    newObj.options[`name${index}`] = item
    })
})

预期值=

 newObj = {
    options: [{name: 'Vegetta'},{name:'Gohan'},{name:'Goku'}]
}

收到的实际值=

newObj = {
  { options: [ name0: 'Vegetta', name1: 'Gohan', name2: 'Goku' ] }}

提前感谢!

推荐答案

正如您所注意到的,newObj.options[`name${index}`] = itemoptions数组上创建了一个新键,并将其设置为item.相反,您希望将形式为{name: item}的对象推入数组中.有几种方法可以做到这一点,其中一种方法是像这样使用.push():

quiz.forEach((item)=>{
  item.options.forEach((item)=>{
    newObj.options.push({name: item});
  })
});

虽然不太常见,但您也可以使用将当前索引设置为options,这与上面的示例略有不同,因为它将保持相同的索引,如果quiz是一个稀疏数组,您希望在options上保持相同的索引,这一点很重要:

quiz.forEach((item)=>{
  item.options.forEach((item, index)=>{
    newObj.options[index] = {name: item};
  })
});

差异示例:

const arr = [1, 2,,,5]; // sparse array
const pushRes = [];
const indxRes = [];

arr.forEach(n => pushRes.push(n));
arr.forEach((n, i) => indxRes[i] = n);
console.log("Push result", pushRes);
console.log("Index result", indxRes);


对于另一种方法,您还可以 Select 使用.flatMap().map()之类的东西来创建options数组,您可以使用它来创建newObj:

const quiz = [
  {question: 'Who is the main character of DBZ',
    options: ['Vegetta','Gohan','Goku']}
];

const options = quiz.flatMap(({options}) => options.map(name => ({name})));
const newObj = {options};
console.log(newObj);

Javascript相关问答推荐

你怎么看啦啦队的回应?

无法访问Vue 3深度监视器中对象数组的特定对象值'

实现JS代码更改CSS元素

如何通过将实例方法的名称传递给具有正确类型的参数的继承方法来调用实例方法?

为什么123[';toString';].long返回1?

回溯替代方式

与svg相反;S getPointAtLength(D)-我想要getLengthAtPoint(x,y)

WebSocketException:远程方在未完成关闭握手的情况下关闭了WebSocket连接.&#三十九岁;

在验证和提交表单后使用useNavigate()进行react 重定向,使用带有加载器和操作的路由

为列表中的项目设置动画

MongoDB中的嵌套搜索

每隔3个项目交替显示,然后每1个项目交替显示

使用Library chart.js在一个带有两个y轴的图表中绘制两个数据集

如何检测当前是否没有按下键盘上的键?

我想为我的Reaction项目在画布上加载图像/视频,图像正在工作,但视频没有

我正在为我的单选按钮在HTML中设置一个值.使用Java脚本,我如何才能获得该值?

如何使用Reaction/Redux创建购物车逻辑?

如何创建在<;span>;中附加每个字符的自定义元素?

如何隐藏SELECT中的第一个选项

将表单数据转换为多维数组