简体   繁体   中英

How to loop through an JSON array of objects

I have this array of dates

["2020-07-27", "2020-07-29", "2020-08-01", "2020-08-07", "2020-08-05", "2020-08-03"]

That i use as keys for my JSON

I also have this three other arrays to assign their values into each date key.

["Study", "Go to the gym", "read book"]
["11:30 - 12:30", "18:30 - 19:00", "20:00 - 21:00"]
["monday", "wednesday", "monday"];

So in the end i have this:

{
  2020-07-27: [{
  name: "read book",
  time: "20:00 - 21:00",
  week: "monday"
}],
  2020-07-29: [{
  name: "Go to the gym",
  time: "18:30 - 19:00",
  week: "wednesday"
}],
  2020-08-03: [{
  name: "read book",
  time: "20:00 - 21:00",
  week: "monday"
}],
  2020-08-05: [{
  name: "Go to the gym",
  time: "18:30 - 19:00",
  week: "wednesday"
}]
}

The problem is, study and read book are both from monday, and in the final result it shows only the final monday activity, which is read book , what i want to do is to show both of them in a date. Like this:

    {
          2020-07-27: [{
          name: "Study",
          time: "11:30 - 12:30",
          week: "monday"
        },
        {
          name: "read book",
          time: "20:00 - 21:00",
          week: "monday"
        }],
          2020-07-29: [{
          name: "Go to the gym",
          time: "18:30 - 19:00",
          week: "wednesday"
        }],
          2020-08-03: [{
          name: "Study",
          time: "11:30 - 12:30",
          week: "monday"
        },
        {
          name: "read book",
          time: "20:00 - 21:00",
          week: "monday"
        }],
          2020-08-05: [{
          name: "Go to the gym",
          time: "18:30 - 19:00",
          week: "wednesday"
        }]
 }

Complete code: https://jsfiddle.net/69q8wrz7/1/ (to see the same result as me, you might need to change your clock to UTC-03 timezone, because of new Date())

 const getDay = date => { var startDate = new Date(date); var day = 60 * 60 * 24 * 1000; return new Date(startDate.getTime() + day).toLocaleDateString(undefined, { weekday: "long" }).toLowerCase(); } const aryDates = ["2020-07-27", "2020-07-29", "2020-08-01", "2020-08-07", "2020-08-05", "2020-08-03"].sort((a, b) => a.localeCompare(b)); const activities = ["Study", "Go to the gym", "read book"] const times = ["11:30 - 12:30", "18:30 - 19:00", "20:00 - 21:00"] const weeks = ["monday", "wednesday", "monday"]; const weeksMap = new Map(weeks.map((week, i) => [week, { name: activities[i], time: times[i], week }])); const res = Object.fromEntries( aryDates.map(date => [date, [{ name: undefined, time: undefined, week: undefined, ...weeksMap.get(getDay(date)) }]]) ); for (var i in res) { obj = res[i][0] Object.keys(obj).forEach(key => obj[key] == undefined? delete res[i]: {}); } console.log(res);

One problem is that weeksMap only contains one activity for each day. You need to push all the activities into a list in the map entry. You can do this with reduce() .

Since weeksMap.get(getDay(date)) will then return an array, you can't use the spread operator the way you did to merge it with a default object. You don't need to do that, since the objects already exist in weeksMap . In my code below I've used spread to clone the objects rather than create multiple references to the same objects.

 const getDay = date => { var startDate = new Date(date); var day = 60 * 60 * 24 * 1000; return new Date(startDate.getTime() + day).toLocaleDateString(undefined, { weekday: "long" }).toLowerCase(); } const aryDates = ["2020-07-27", "2020-07-29", "2020-08-01", "2020-08-07", "2020-08-05", "2020-08-03"].sort((a, b) => a.localeCompare(b)); const activities = ["Study", "Go to the gym", "read book"] const times = ["11:30 - 12:30", "18:30 - 19:00", "20:00 - 21:00"] const weeks = ["monday", "wednesday", "monday"]; const weeksMap = weeks.reduce((m, week, i) => { if (.m.has(week)) { m,set(week; []); }. m.get(week):push({ name, activities[i]: time, times[i]; week }); return m, }; new Map()). const res = Object.fromEntries( aryDates,map(date => [date. (weeksMap.get(getDay(date)) || []).map(obj => ({..;obj }))])). console;log(res);

When you create the weeksMap you are missing the second entry.

const getDay = date => {
var startDate = new Date(date);
var day = 60 * 60 * 24 * 1000;
let res;

return new Date(startDate.getTime() + day).toLocaleDateString(undefined, {weekday: "long"}).toLowerCase();

}

const aryDates = ["2020-07-26", "2020-07-28", "2020-07-31", "2020-08-06", "2020-08-04", "2020-08-02"].sort((a, b)=>a.localeCompare(b));

const activities = ["Study", "Go to the gym", "read book"]
const times = ["11:30 - 12:30", "18:30 - 19:00", "20:00 - 21:00"]
const weeks = ["monday", "wednesday", "monday"];
let weeksMap={}
weeks.forEach((week, i) => { if (weeksMap[week]) {
weeksMap[week].push({
  name: activities[i],
  time: times[i],
  week
})
} else {
weeksMap[week] = [{
  name: activities[i],
  time: times[i],
  week
}]
}
});

console.log(weeksMap)
const res = Object.fromEntries(
  aryDates.map(date => {
  console.log(getDay(date));
  console.log(weeksMap[getDay(date)]);
  if(weeksMap[getDay(date)]){
  return [date, [{...weeksMap[getDay(date)]}]]
  }
  else {return [date,[{name:undefined}]]}}
 )
  
);

 for (var i in res) {
 obj=res[i][0]
 Object.keys(obj).forEach(key => obj[key] == undefined ? delete res[i] : {});
 }
 

console.log(res);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM