尝试通过引用单独的json设置值

时间:2019-02-02 09:37:35

标签: javascript node.js json

我试图将模型的功能和数据分开,所以我用基本表创建了一个单独的json文件

在构建模型时,它会创建一个对象,我需要它根据传入的值在其中创建一个值:

{
"1":"apple",
"2":"banana",
"3":"orange",
"4":"grape"
}

  async save (xmlOrder) {
    let customerOrder = {
      ID: xmlOrder.ID,
      Name: xmlOrder.Name ,
      ItemCode: xmlOrder.ItemCode ,
      Fruit: (This set by referencing the json, based on the Item code coming in above)enter code here
    }

1 个答案:

答案 0 :(得分:1)

您可以将该json对象导入模型所在的文件中,而不是根据功能的输入来获取对象的价值。

let obj = {"1":"apple","2":"banana","3":"orange","4":"grape"}

function save (xmlOrder) {
  let customerOrder = {
     ID: xmlOrder.ID,
     Name: xmlOrder.Name ,
     ItemCode: xmlOrder.ItemCode ,
     Fruit: obj[xmlOrder.ItemCode] || 'Not in list',
   }
 return customerOrder
}

console.log(save({ID:33,Name:'Name',ItemCode:'2'}))
console.log(save({ID:303,Name:'Name1',ItemCode:'21'}))