Javascript循环并将键存储为变量并从存储的键输出其他字段?

时间:2014-06-25 03:53:15

标签: javascript underscore.js

我是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"
        }
    }
}

到目前为止,我已经粗暴地强迫它,明确地定义了所有的skus,它是愚蠢的:

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
    }
  }
}

1 个答案:

答案 0 :(得分:1)

我明白了。

//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
    }
  }
}