遍历数组JS的对象数组

时间:2018-12-28 10:27:40

标签: javascript arrays object

我如何遍历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)) );

    }

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

enter image description here

在问题中添加数组的方法如下:

您需要对其进行迭代:

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的第一个元素