【问题标题】:How can I better save child objects of all objects in array?如何更好地保存数组中所有对象的子对象?
【发布时间】:2020-06-09 03:24:44
【问题描述】:

所以我在 Vue 中创建了一个项目,我想遍历所有 ['monitors'] 并保存不同的离开。我如何以最好的方式做到这一点? 谢谢!

<script>

listOfAllTrips = this.wlData['monitors'][0].lines[0].departures;
listOfAllTrips2 = this.wlData['monitors'][1].lines[0].departures;
listOfAllTrips3 = this.wlData['monitors'][2].lines[0].departures;

</script>

【问题讨论】:

  • listOfAllTrips = this.wlData['monitors'].map(monitor =&gt; monitor.lines[0].departures);
  • 非常感谢 ritaj,这正是我想要的! :-)

标签: javascript arrays loops vue.js object


【解决方案1】:

你可以使用map函数和解构赋值如下:

let m = [{lines: [{departures: ["Ele", "Stack"]}]}, {lines: [{departures: ["Ele2", "Stack2"]}]}];
let result = m.map(({lines: [departures]}) => departures);
console.log(result);

【讨论】:

    【解决方案2】:
     let listOfAllTrips = [];
     this.wlData['monitors'].map((data,k)=>{
        listOfAllTrips.push(data.lines[0].departures);
     })
    

    这是一个使用 Ecma Script 数组映射函数的迭代,它将处理所有行程列表超过 3 个正式硬编码的情况。

    现在要访问每个出发点,您只需提供访问索引,例如

    listOfAllTrips[1]
    

    这将返回数组索引从 0 开始的第二次行程

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      相关资源
      最近更新 更多