gpt4 book ai didi

javascript - 获取当前对象中先前对象的值

转载 作者:行者123 更新时间:2023-12-01 01:27:59 25 4
gpt4 key购买 nike

我使用的数据集包含大约65k 数据。我多次映射数据集以调整数据集。获得所需格式的数据集后,我使用 map 对当前商品的价格进行一些计算。但是,每当我返回当前对象时,它都会包含前一个对象的计算数据。

每当我记录数据时,它总是显示当前对象以及基于当前对象的计算。但是,返回的对象包含前一个对象的数据。路线如下:

const {priceBands} = require('../utils/profitComputations');

let profitArray = [];

//calculating the price bands
profitArray = _.map(nfoArray, item=>{
console.log(item.cmp);
//returns the current market price; getting the correct value here

let priceBandVar = priceBands(Number(item.cmp));
console.log(priceBandVar);
//applying some algorithms; getting the correct value here

return {item: item.cmp, profitBand: priceBandVar};
//Here I find a mismatch between the parameter and the calculations

});

这是我的'utils/profitComputations'中的priceBands函数:

const _ = require('lodash');
const priceBandInterval = {'-4':0, '-3':0, '-2':0, '-1':0, '0floor':0,'0ceil':0,'1':0, '2':0, '3':0, '4':0};
let priceBands = {};
module.exports = {
priceBands: function(price){
let factor = 0;
if(price>=10000){
factor = 100;
}else if (price>=1000 && price<10000){
factor = 50;
}else if (price>=500 && price<1000){
factor = 25;
}else if (price>=100 && price<500){
factor = 10;
}else if(price>=25 && price<100){
factor = 2;
}else{
factor = 0.5;
}
let priceCeil, priceFloor;
if((price%factor) == 0){
priceCeil = price + factor;
priceFloor = price - factor;
} else {
const remainder = price%factor;
priceCeil = price - remainder + factor;
priceFloor = price - remainder;
}
_.map(Object.keys(priceBandInterval), item=>{
if(parseInt(item)>0){
priceBands[item] = (parseInt(item)*factor) + priceCeil;
} else if (parseInt(item)<0){
priceBands[item] = (parseInt(item)*factor) + priceFloor;
} else {
priceBands['0floor'] = priceFloor;
priceBands['0ceil'] = priceCeil;
}
});
return priceBands;
}
}

如果有人能够分享一些关于我所缺少的内容的宝贵见解,我将不胜感激。

最佳答案

您必须克隆变量 priceBandVar,因为 javaScript 变量是通过引用调用的。以下代码就是您的答案:

profitArray = _.map(nfoArray, item => {
console.log(item.cmp);
//returns the current market price; getting the correct value here

let priceBandVar = priceBands(Number(item.cmp));
console.log(priceBandVar);
//applying some algorithms; getting the correct value here

return {
item: item.cmp,
profitBand: clone(priceBandVar)
};
//Here I find a mismatch between the parameter and the calculations

});

function clone(o) {
var ret = {};
Object.keys(o).forEach(function(val) {
ret[val] = o[val];
});
return ret;
}

关于javascript - 获取当前对象中先前对象的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53577580/

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