循环嵌套的JavaScript对象

时间:2018-02-04 18:46:20

标签: javascript angular typescript

我在我的项目中使用Angular 5,我想循环一个看起来像这样的JavaScript对象:

var items = [
    {
        "departure": "new york",
        "arrival": "new jersy",
        "stations": [
            { "station": "new_1" },
            { "station": "new_2" },
            { "station": "new_3" },
            // ...
        ]
    }
];

这里是代码:

generateStationPriceMethode(items: any) {
    if (items.stations.length > 0) {
        let user = {
            "stationPrice": "00",
            "stationName": items.departure + "-" + items.stations[0].station,
        };

        this.setItem<priceStation>(this.myObject, (u) => u.station == station, user);
        for (let i = 0; i < items.stations.length; i++) {
            alert('eee');
            let user = {
                "stationPrice": "00",
                "stationName": items.stations[i].station + "-" + items.stations[i + 1].station,
            };
            this.setItem<priceStation>(this.myObject, (u) => u.station == station, user);
        }

    } else if (!items.stations.length) {
        let user = {
            "stationPrice": "00",
            "stationName": items.departure + "-" + items.arrival,
        };

        this.setItem<priceStation>(this.myObject, (u) => u.station == station, user);
    }

    console.log("youssef :" + JSON.stringify(this.obj.StationPrice));
}

另一个功能:

setItem<T>(array: Array < T >, predicate: Predicate < T >, item: T) {
    var _oldItem = _.find(array, predicate);
    if (_oldItem) {
        var index = _.indexOf(array, _oldItem);
        array.splice(index, 1, item);
    } else {
        array.push(item);
    }
}

执行generateStationPriceMethode时,会抛出此错误:

  

ERROR ReferenceError:未定义工作站

我想从generateStationPriceMethode得到的是这个对象:

var myObject = [
    { "stationPrice": "00", "stationName": "new york - new_1"},
    { "stationPrice": "00", "stationName": "new_1 - new_2" },
    { "stationPrice": "00", "stationName": "new_2 - new_3" },
    { "stationPrice": "00", "stationName": "new york - new jersy" },
];

items.stations.length < 0(我的意思是台对象不存在)时,我想要获得这个对象:

var myObject = [
    {
        "stationPrice": "00",
        "stationName":"new york - new jersy",
    },
];

2 个答案:

答案 0 :(得分:0)

您可以使用reduce功能。

请查看此代码段。

var items = [{
  "departure": "new york",
  "arrival": "new jersy",
  "stations": [
    {"station": "new_1"}, 
    {"station": "new_2"},
    {"station": "new_3"}
  ]
}];

var getStations = function() {
  var stations = [];
  items.forEach((sts) => {
    if (sts.stations === undefined || sts.stations.length === 0)  {
      stations.push({
        "stationPrice": "00",
        "stationName": `${sts.departure} - ${sts.arrival}`
      });

      return false;
    }

    stations = [...[sts.departure], ...sts.stations.map((s) => s.station)].reduce((a, c, i, arr) => {
      if (i + 1 === arr.length) {
        a.push({
          "stationPrice": "00",
          "stationName": `${arr[i]} - ${sts.arrival}`
        });

        return a;
      };

      a.push({
        "stationPrice": "00",
        "stationName": `${c} - ${arr[i + 1]}`
      });

      return a;
    }, []);

    stations.push({
      "stationPrice": "00",
      "stationName": `${sts.departure} - ${sts.arrival}`
    });

  });

  return stations;
};

console.log(getStations(items));

items = [{
  "departure": "new york",
  "arrival": "new jersy",
  "stations": []
}];

console.log('------- Stations = []');
console.log(getStations(items));

items = [{
  "departure": "new york",
  "arrival": "new jersy"
}];
console.log('------- Stations = undefined');
console.log(getStations(items));
.as-console-wrapper {
  max-height: 100% !important
}
myObject=[{"stationPrice": "00", "stationName":"new york - new_1"},{"stationPrice": "00", "stationName":"new_1 - new_2"}, {"stationPrice": "00", "stationName":"new_2 - new_3"},....,{"stationPrice": "00", "stationName":"new york - new jersy"}]

资源

Array.prototype.reduce()

更新

下面的代码是什么

[...[sts.departure], ...sts.stations.map((s) => s.station)]

首先,您需要阅读一些关于Spread operator的内容。

该行返回以下内容:

["new york", "new_1", "new_2", "new_3"]

答案 1 :(得分:0)

我不认为让你排成一阵是个好主意。 你确定你不想要一系列可能的路线吗?或者你确定你只有1个项目吗?

但你可以这样做:

&#13;
&#13;
const forLoopiNSeria = async () => {
  for(var i = 0; i < 10; i++){
    console.log(await doSomething(i))
  }
}


function doSomething(index) {
  return new Promise( (resolve, reject) => {
    setInterval(() => resolve(index), 500)
  }) 
}

forLoopiNSeria()
&#13;
&#13;
&#13;