javascript - 我想创建一个对象数量等于植物数组中 obj 数量的数组
问题描述
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',
// }
// ]
// }
// ]
任何帮助表示赞赏
解决方案
只需映射原始植物并使用标签。
let newArray = resp.plants.map((plant) => ({
label: resp.label,
plant,
});
你得到这个结果的原因是你浅拷贝了对象,对该变量的任何更改都会影响原始变量。
推荐阅读
- php - 当用户订阅多个价格计划时,Laravel Cashier Stripe PRICE 在订阅表中为空?
- javascript - 如何激活 ReCharts 面积图中的特定数据点?
- excel - Powershell脚本搜索excel文件目录以查找仅搜索1个文件的字符串
- html - 从表单组中选择后,为什么无法突出显示单个单选
- aws-lambda - 使用 IdentityPool Id (cognito-identity.amazonaws.com:aud) 的 DynamoDB 细粒度访问控制
- python - 如何将数据转换为所需格式并写入文件 - Python + Apache Beam
- google-cloud-platform - 无法访问 GCP 虚拟机实例
- python - 将 NaN 值移动到 df 的末尾
- angular - 在 Angular 中导航页面时按钮状态发生变化
- azerothcore - 献祭移除延迟