简体   繁体   English

Js从数组复制对象而无需引用

[英]Js copy objects from array without reference

I hava a problem with copy a objects to array. 我在将对象复制到数组时遇到问题。 I think it is an problem with reference. 我认为这是一个参考问题。

In my program i have few array. 在我的程序中,我几乎没有数组。 First is dataForMonth - it is array of objects with data for month. 首先是dataForMonth-它是具有月份数据的对象数组。 And second is an products array which contains products objects. 第二个是包含产品对象的产品数组。 Product have property forecastArry wchich is array of objects. 产品具有属性ForecastArry wchich是对象数组。

Here code : 这里的代码:

this.allProducts.map(function (product) {

            var dataForMonth = data.filter(function (e) {
                return e.dataId === product.productDataId;
            });

            var z = { posId: product.sales_plan_pos_id, arry: [] }
            for (var sheetMonth of sheet.channels) {
                var result = dataForMonth.filter(function (e) {
                    return e.CHANNEL === sheetMonth.CHANNEL;
                });

           product.forecastArry[someId].channels = result;
); 

The problem is that the every changed channels property have the same value - its a value from last product? 问题在于,每个更改的通道属性都具有相同的值-它是上一个产品的值吗? Anybody know how to fix it ? 有人知道如何解决吗?

Seems like you want to edit each product in this.allProducts . 好像您要编辑this.allProducts每个product So you want to add a return value to your map. 因此,您想向地图添加返回值。 You should also use let so that the scope of variables declared is preserved within map function, although I believe the map function already takes care of that. 您还应该使用let以便将声明的变量的范围保留在map函数内,尽管我相信map函数已经在解决这个问题。 In addition, not that you have to reassign this.allProducts to your map function call. 另外,不必将this.allProducts重新分配给地图函数调用。 So your answer should be something like the following: 因此,您的答案应类似于以下内容:

 this.allProducts = this.allProducts.map(function (product) { let dataForMonth = data.filter(function (e) { return e.dataId === product.productDataId; }); let channelsForMont = []; let z = { posId: product.sales_plan_pos_id, arry: [] } for (let sheetMonth of sheet.channels) { let result = dataForMonth.filter(function (e) { return e.CHANNEL === sheetMonth.CHANNEL; }); product.forecastArry[someId].channels = channelsForMont; return product; ); 

PS Your original code has some missing brackets and result variable is unused. PS您的原始代码缺少一些方括号,并且未使用result变量。 You should do something about them. 您应该对它们采取措施。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM