循环返回相同的值

时间:2019-05-04 06:13:41

标签: javascript

我需要用另一个数组中的值替换模板数组,并将其推送到最终结果。 这是我尝试过的问题,问题是循环时我得到的值相同。

  var pickups = [
    { address: "Lusaka, Zambia", distance: 22 },
    { address: "Ndola, Zambia", distance: 44 }
  ];

  var template = [{ lable: "distance", data: 0 }];

  var final_templates = [];

  var pickup_temp = template;

  for (var i = 0; i < pickups.length; i++) {
    for (var m = 0; m < template.length; m++) {
      if (pickup_temp[m].lable == "distance") {
        pickup_temp[m].data = pickups[i].distance;
      }
    }
    final_templates.push(pickup_temp);
  }

  console.log(final_templates);

预期结果:

[[{lable: "distance", data: 22}],[{lable: "distance", data: 44}]]

实际结果(相同的距离值):

[[{lable: "distance", data: 44}],[{lable: "distance", data: 44}]]

1 个答案:

答案 0 :(得分:0)

如果代码避免for循环而仅使用Array.map,则更简单:

  var pickups = [
    { address: "Lusaka, Zambia", distance: 22 },
    { address: "Ndola, Zambia", distance: 44 }
  ];

  var template = [{ lable: "distance", data: 0 }];

  var final = pickups.map(pick => (
      template.map( item => (
          { label: item.lable, data: pick[item.lable] }
      ))
  ));

  console.log(JSON.stringify(final));