如何获取与JSON中的时间相同的所有天数名称?

时间:2018-10-10 11:42:21

标签: javascript json

var data = {
"fri": {
  "to_time": "16:00",
  "from_time": "10:00"
},
"mon": {
  "to_time": "16:00",
  "from_time": "14:00"
},
"sat": {
  "to_time": "16:00",
  "from_time": "10:00"
},
"sun": {
  "to_time": "13:00",
  "from_time": "10:00"
},
"thu": {
  "to_time": "16:00",
  "from_time": "14:00"
},
"tue": {
  "to_time": "16:00",
  "from_time": "10:00"
},
"wed": {
  "to_time": "16:00",
  "from_time": "10:00"
}
}

如何使所有时间与from_time相同?

2 个答案:

答案 0 :(得分:3)

您可以同时带一个物体和想要的时间来收集日期。

var data = { fri: { to_time: "16:00", from_time: "10:00" }, mon: { to_time: "16:00", from_time: "14:00" }, sat: { to_time: "16:00", from_time: "10:00" }, sun: { to_time: "13:00", from_time: "10:00" }, thu: { to_time: "16:00", from_time: "14:00" }, tue: { to_time: "16:00", from_time: "10:00" }, wed: { to_time: "16:00", from_time: "10:00" } },
    groups = ['from_time', 'to_time'],
    grouped = Object.entries(data).reduce((accumulator, [day, object]) => {
        var key = groups.map(group => object[group]).join();
        (accumulator[key] = accumulator[key] || []).push(day);
        return accumulator;
    }, Object.create(null));
    
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

var data = { fri: { to_time: "16:00", from_time: "10:00" }, mon: { to_time: "16:00", from_time: "14:00" }, sat: { to_time: "16:00", from_time: "10:00" }, sun: { to_time: "13:00", from_time: "10:00" }, thu: { to_time: "16:00", from_time: "14:00" }, tue: { to_time: "16:00", from_time: "10:00" }, wed: { to_time: "16:00", from_time: "10:00" } };

var myArr = [];
//Loop through object
for (var i in data) {
  for (var j in data) {
    if (i != j && data[i].from_time == data[j].from_time && data[i].to_time == data[j].to_time) {
      if (myArr.indexOf(i) == -1) {
        myArr.push(i);
      }
    }
  }
}

console.log(myArr);