【发布时间】:2021-08-11 12:19:38
【问题描述】:
forEach循环后,所有索引中的对象值发生变化,如何用当前索引限制它
resp = {
label:'flowers',
plants: [
{
plantLabel: 'rose',
plantCode: 'RS',
},
{
plantLabel: 'Jasmine',
plantCode: 'JAS',
},
{
plantLabel: 'Lotus',
plantCode: 'LU',
}
]
};
loop() {
let newArray = [];
let tempResp = this.resp;
const val = chunk(tempResp.plants, 1);
console.log(val);
val.forEach(plant => {
let pushValue = tempResp;
pushValue.plants= plant;
newArray.push(pushValue);
});
**//expected
// [
// {
// label:'flowers',
// plants: [
// {
// plantLabel: 'rose',
// plantCode: 'RS',
// }
// ]
// },{
// label:'flowers',
// plants: [
// {
// plantLabel: 'Jasmine',
// plantCode: 'JAS',
// }
// ]
// },{
// label:'flowers',
// plants: [
// {
// plantLabel: 'Lotus',
// plantCode: 'LU',
// }
// ]
// }
// ]**
但我得到的结果是
// [
// {
// label:'flowers',
// plants: [
// {
// plantLabel: 'Lotus',
// plantCode: 'LU',
// }
// ]
// },{
// label:'flowers',
// plants: [
// {
// plantLabel: 'Lotus',
// plantCode: 'LU',
// }
// ]
// },{
// label:'flowers',
// plants: [
// {
// plantLabel: 'Lotus',
// plantCode: 'LU',
// }
// ]
// }
// ]
感谢任何帮助
【问题讨论】:
-
为什么预期的和实际的输出被不必要地注释了?
-
标题是什么"我想创建一个包含多个对象的数组..." 与 "...对象值发生变化所有索引,如何用当前索引限制它” 在问题的正文中?
-
请添加大括号结束
loop函数。chunk函数中有什么?
标签: javascript arrays typescript