从JS配置对象中提取数据以创建新对象

时间:2016-07-07 15:36:59

标签: javascript foreach configuration lodash

给这个配置对象成员(一个更大的对象的一部分):

catch (Exception $e) {
  $errorMessage = $e->getMessage();
  if($errorMessage=='Coupon is not redeemable.')
  {
    $myerrorCode=1;
  }
  //Add more else if, or case switch statement to handle the various errors you want to handle
  print $myErrorMsg[$myerrorCode]; // array of my custom messages.
}

我需要迭代它并为站点数组中的每个对象生成此对象:

  stations: [
    {
      id: "RH",
      positions: ['RH2,', 'RH16', 'RH14']
    },
    {
      id: "WT",
      positions: ['WT10,', 'WT11', 'WT12', 'WT13', 'WT14', 'WT18']
    },
    {
      id: 1,
      positions: ['AO,', 'FF', 'PFF']
    },
    {
      id: 2,
      positions: ['AO,', 'FF', 'PFF']
    },
    {
      id: 3,
      positions: ['AO,', 'FF', 'PFF']
    },
    {
      id: 4,
      positions: ['AO,', 'FF', 'PFF']
    }
  ],

我会单独填写这个名字,所以我现在并不担心这个价值。

我一直试图用lodash _.forEach()来做这件事,但我有一种感觉,我并没有尽可能有效地使用它。我试图做的(并且失败的)是在另一个内部使用_.forEach(),而我无法从内部循环访问外部循环中的变量:

var myObj = {
  "station": 1,
  "slots": [
    {
      "position": "AO" 
      "name": [name]
    },
    {
      "position": "FF" 
      "name": [name]
    },
    {
      "position": "PFF" 
      "name": [name]
    },
  ]  
}

(这只是为了展示我尝试做的事情 - 不使用代码)。

那么我怎样才能完成我想要做的事情呢?

感谢。

1 个答案:

答案 0 :(得分:0)

以下是包含两个forEach()循环的简单javascript解决方案。

var data ={"stations":[{"id":"RH","positions":["RH2,","RH16","RH14"]},{"id":"WT","positions":["WT10,","WT11","WT12","WT13","WT14","WT18"]},{"id":1,"positions":["AO,","FF","PFF"]},{"id":2,"positions":["AO,","FF","PFF"]},{"id":3,"positions":["AO,","FF","PFF"]},{"id":4,"positions":["AO,","FF","PFF"]}]}

var result = [];

data.stations.forEach(function(o) {
  var obj = {station: o.id, slots: []}
  o.positions.forEach(function(e) {
    obj.slots.push({
      position: e,
      name: "Name"
    })
  })
  result.push(obj);
});

document.body.innerHTML += '<pre>' + JSON.stringify(result, 0, 4) + '</pre>';