javascript - 为什么更改后对连接数组的操作会影响两个数组?
问题描述
我运行以下过程以从对象中收集所有产品属性和选项,以更新产品。
出于某种奇怪的原因,主数组 categoryUrls 发生了变化,我似乎无法理解为什么。
在以下过程之后,categoryUrls[random key].attributes.options
获取添加的新值。
const {categoryUrls} = require('./helpers/categoryUrls.js')
getCategory = function (categoryUrls) {
let att = []
for (const key in categoryUrls) {
if (categoryUrls[key].attributes) {// check if has attribute
att = att.concat(categoryUrls[key].attributes)
for(var i=0; i<att.length; ++i) {// check if attribute ID already exist and remove duplicates
for(var j=i+1; j<att.length; ++j) {
if(att[i].id === att[j].id){
for (let k = 0; k < att[j].options.length; k++) { // if attribute ID already exist unite options
let exist = att[i].options.find(option => option == att[j].options[k]) // check if option no already exist
if (!exist) {
att[i].options.push(att[j].options[k])
}
}
att.splice(j--, 1);
}
}
}
}
}
return att
}
let data = getCategory(categoryUrls)
productData = productData.concat(data)
解决方案
如果我理解您正在尝试将新数组保存到att
中,但让原始数组保持不变,但您正在将过程应用到 categoryUrls。那是对的吗?如果是这样,请记住数组是引用类型,因此,如果您使用它们,您会更改实际的数组,它们不会作为字符串或整数工作。
尝试在工作之前复制阵列并将该过程应用于其副本。
尝试这个:
const {categoryUrls} = require('./helpers/categoryUrls.js')
getCategory = function (categoryUrls) {
let newArray = [...categoryUrls]
let att = []
for (const key in categoryUrls) {
if (categoryUrls[key].attributes) {// check if has attribute
att = att.concat(newArray[key].attributes)
for(var i=0; i<att.length; ++i) {// check if attribute ID already exist and remove duplicates
for(var j=i+1; j<att.length; ++j) {
if(att[i].id === att[j].id){
for (let k = 0; k < att[j].options.length; k++) { // if attribute ID already exist unite options
let exist = att[i].options.find(option => option == att[j].options[k]) // check if option no already exist
if (!exist) {
att[i].options.push(att[j].options[k])
}
}
att.splice(j--, 1);
}
}
}
}
}
return att
}
let data = getCategory(categoryUrls)
productData = productData.concat(data)
推荐阅读
- javascript - 我想解密使用 openssl_encrypt 在 php 中加密的文本
- java - 导入apache poi时getResourceAsStream返回null?
- python - 订阅 websocket 后如何解析数据
- git - 在 Git 中变基时 COMMIT 会丢失什么?
- python - 使用熊猫数据框中的两列计算加权和
- amazon-web-services - 如何在 docker 容器中运行 AWS CW 代理?
- reactjs - 反应路由器 POP
- c - 如何将文件中的字符串列表读入动态二维数组,然后在 C 中对其进行排序
- spring-boot - Spring Boot 中的应用程序上下文
- java - 通过使用java单击“浏览名称”按钮将名称导入名字和姓氏文本字段