【问题标题】:Iterate through array of objects of array JS遍历数组JS的对象数组
【发布时间】:2018-12-28 10:27:40
【问题描述】:

我如何在 JS 中遍历这样的结构,基本上它是一个包含对象数组的数组 这就是我在 console.log 时得到的结果

[Array(1)]
0: Array(1)
0: {day: "Friday", start: "2:00", end: "7:30"}
length: 1
__proto__: Array(0)
length: 1
__proto__: Array(0)

我试过了

formattedShifts.map(shift => shift.end)

但它失败了,formattedShifts 是我推入的数组 这是我创建数组的地方

  let formattedShifts = [];
    if(props.formData.isLinkedShifts) {
      //converts shift.startTime and shift.endTime format 
      function toDays(startDateString, endDateString) {
        const formatString = 'ddd MMM DD YYYY HH:mm:ss [GMT]ZZ';
        const startDate = moment(startDateString, formatString);
        const endDate = moment(endDateString, formatString);
        const start = startDate.format('H:mm');
        const end = endDate.format('H:mm');

        const dates = [];

        while(startDate.isSameOrBefore(endDate, 'day')) {
          let currentDay = startDate.format('dddd');
          dates.push({day: currentDay, start: start, end: end});
          startDate.add(1, 'days');
        }
        return dates;
      }
      formattedShifts.push( toDays( props.formData.shifts.map( shift => shift.startTime), 
        props.formData.shifts.map( shift => shift.endTime)) );

    }

【问题讨论】:

  • 不要添加阵列的控制台日志。请添加实际数组
  • 检查编辑,应该不错

标签: javascript arrays object


【解决方案1】:

根据您的控制台结果,我假设您的数组类似于

Var a = [
  {
    day: "Friday", 
    start: "2:00", 
    end: "7:30"
  }
]

所以你可以像这样遍历,

a.forEach(function(item) {console.log(item)})   //{day: "Friday", start: "2:00", end: "7:30"}

a.forEach(function(item) {
  for (i in item) { 
     console.log(i, item[i])
  }
})

控制台结果会像

day Friday // i will give the key (day), item[i] will give the value of key (Friday)
start 2:00
end 7:30

【讨论】:

    【解决方案2】:

    因为您在问题中添加了这样的数组:

    你需要迭代它:

    var a = [[{day: "Friday", start: "2:00", end: "7:30"}, {day: "Friday", start: "2:00", end: "12:30"},{day: "Friday", start: "2:00", end: "8:30"} ,{day: "Friday", start: "2:00", end: "09:30"}]]
    
    const ends = a[0].map(value => value.end);
    
    console.log(ends)

    您需要遍历 array of array of object 的第一个元素

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-08
      • 1970-01-01
      • 2017-09-19
      • 1970-01-01
      相关资源
      最近更新 更多