gpt4 book ai didi

javascript嵌套forEach,typeError

转载 作者:行者123 更新时间:2023-11-30 07:12:38 25 4
gpt4 key购买 nike

我正在执行双重 forEach,但在尝试重建另一个对象时出现类型错误:

const users = [
{teacher: [
{file: 'chemistry', size: '2MB'},
{file: 'math', size: '1MB'}]
}, {student: [
{file: 'chemistry', size: '3MB'},
{file: 'math', size: '4MB'}]
}
];

let final = {};

users.forEach(function(i) {

i.forEach(function(j){
let filesizestring = 'newfilesize'+j.size;
final[j] = j;
final.j[j.file] = filesizestring;
})
})

预期的结果是:

{teacher: {
chemistry: 'newfilesize2MB',
math: 'newfilesize1MB'
},
student: {
chemistry: 'newfilesize3MB',
math: 'newfilesize4MB'
}
}

有人可以帮我解决这个问题吗?

更新

如果嵌套 forEach 是不可能的,我怎样才能达到相同的结果?

最佳答案

你在 i -> i.forEach(function(j) 上执行循环,但是,i 是一个对象,所以你需要循环对象键值对使用 for (key in i) 并且对于每个 key 获取数组如下 i[key]

const users = [{
teacher: [{
file: 'chemistry',
size: '2MB'
},
{
file: 'math',
size: '1MB'
}
]
}, {
student: [{
file: 'chemistry',
size: '3MB'
},
{
file: 'math',
size: '4MB'
}
]
}];

let final = {};

users.forEach(function(i) {
for (key in i) {
var obj = {};
i[key].forEach(function(j) {
let filesizestring = 'newfilesize' + j.size;
obj[j.file] = filesizestring;
});
final[key] = obj;
}
});

console.log(final);

希望对您有所帮助!

关于javascript嵌套forEach,typeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48384247/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com