gpt4 book ai didi

Javascript 循环并将键存储为变量并从存储的键中输出附加字段?

转载 作者:行者123 更新时间:2023-12-03 12:22:09 26 4
gpt4 key购买 nike

我对 JS 和编码不太熟悉,所以我不确定如何有效地为此编写一个函数。我想编写一个函数,它接受一个对象作为参数并返回另一个对象。

OrderFormContents = {
servicesSelected: {
hdrPhotos: "selected",
panos: "selected",
twilightPhotos: "selected"
}
}

hdrPhotospanostwilightPhotos 都是 SKU/唯一标识符。

我想返回一个像这样的对象:

CompletedOrderFormContents = {
servicesSelected: {
hdrPhotos: {
sku: "hdrPhotos",
calculatedPrice: 100, // returned from an object stored as a Session variable called calculatedPrices
title: "HDR Photography" //returned from looking up the sku from a Services collection.
},
panos: {
sku: "panos",
calculatedPrice: 125,
title: "Panoramas"
},
twilightPhotos: {
sku: "twilightPhotos",
calculatedPrice: 200,
title: "Twilight Photography"
}
}
}

到目前为止,我一直在暴力破解它,明确定义所有的 sku,但它很愚蠢:

var myFunction = function(OrderFormContents) {

CompletedOrderFormContents = {
servicesSelected: ""
};

CompletedOrderFormContents.servicesSelected.hdrPhotos = {
sku: "hdrPhotos",
calculatedPrice: Session.get("calculatedPrices").hdrPhotos,
title: Services.find({"sku" : "hdrPhotos"}).fetch()[0].title
};

CompletedOrderFormContents.servicesSelected.panos = {
sku: "panos",
calculatedPrice: Session.get("calculatedPrices").panos,
title: Services.find({"sku" : "panos"}).fetch()[0].title
};

CompletedOrderFormContents.servicesSelected.twilightPhotos = {
sku: "twilightPhotos",
calculatedPrice: Session.get("calculatedPrices").twilightPhotos,
title: Services.find({"sku" : "twilightPhotos"}).fetch()[0].title
};

};

我将如何重构此代码,以便至少不会为每个语句显式定义 SKU 并为每个 SKU 显式定义每个语句?我已经安装了 UnderscoreJS。

编辑让它工作。

completedOrderFormContents = {
servicesSelected: {}
};

for (sku in OrderFormContents.servicesSelected) {
if (OrderFormContents.servicesSelected.hasOwnProperty(sku)) {
completedOrderFormContents.servicesSelected[sku] = {
sku: sku,
price: Session.get("calculatedPrices")[sku],
title: Services.find( { "sku" : sku }).fetch()[0].title
}
}
}

最佳答案

我成功了。

//servicesSelected does not currently exist in completedOrderFormContents, 
//so gotta create it - ie. simply doing completedOrderFormContents = {} would not work
//because the for loop is going to try and assign something to .servicesSelected
//later on and it needs that .servicesSelected key to already be there

completedOrderFormContents = {
servicesSelected: {}
};

for (sku in OrderFormContents.servicesSelected) {
if (OrderFormContents.servicesSelected.hasOwnProperty(sku)) {
completedOrderFormContents.servicesSelected[sku] = {
sku: sku,
price: Session.get("calculatedPrices")[sku],
title: Services.find( { "sku" : sku }).fetch()[0].title
}
}
}

关于Javascript 循环并将键存储为变量并从存储的键中输出附加字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24399889/

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