var person = {
course1:{Name:"xxx", day:"mon", time:"2am-6pm"},
course2:{Name:"yyy", day:"tue", time:"7am-9pm"},
course3:{Name:"zzz", day:"tue", time:"2am-6pm"},
course4:{Name:"aaa", day:"wed", time:"2am-6pm"},
course5:{Name:"bbb", day:"thu", time:"2am-6pm"},
course6:{Name:"ccc", day:"mon", time:"2am-6pm"}
};
任何人都可以展示如何循环和遍历此人物对象并交换course1和course2对象值(名称,日期,时间)并做一些事情,替换它并交换course1和course3再做一些事情等等。
答案 0 :(得分:1)
您可以使用Object.keys
来获取所有键组,然后您可以迭代它。
类似的东西:
const person = {
course1: {
Name: "xxx",
day: "mon",
time: "2am-6pm"
},
course2: {
Name: "yyy",
day: "tue",
time: "7am-9pm"
},
course3: {
Name: "zzz",
day: "tue",
time: "2am-6pm"
},
course4: {
Name: "aaa",
day: "wed",
time: "2am-6pm"
},
course5: {
Name: "bbb",
day: "thu",
time: "2am-6pm"
},
course6: {
Name: "ccc",
day: "mon",
time: "2am-6pm"
}
};
Object.keys(person).forEach((key) => {
const course = person[key];
// Do your logic here...
});

答案 1 :(得分:1)
const person = {
course1:{Name:"xxx", day:"mon", time:"2am-6pm"},
course2:{Name:"yyy", day:"tue", time:"7am-9pm"},
course3:{Name:"zzz", day:"tue", time:"2am-6pm"},
course4:{Name:"aaa", day:"wed", time:"2am-6pm"},
course5:{Name:"bbb", day:"thu", time:"2am-6pm"},
course6:{Name:"ccc", day:"mon", time:"2am-6pm"}
};
const courses = Object.keys(person).filter(course => course !== 'course1');
courses.forEach(key => {
const copyOne = Object.assign({}, person['course1']);
const copyCurrent = Object.assign({}, person[key]);
person['course1'] = copyCurrent;
person[key] = copyOne;
});
console.log(person);
您希望在每次迭代时与course1
进行比较,因此在forEach
中使用密钥没有意义。
答案 2 :(得分:1)
// find the least expensive course
// for easier coding, set a cost property for each course.
for(let course in person) {
course['cost'] = getCourseCost(course);
}
let lowestCostCourse = person['course1'];
// this compares person['course1'] to itself, but so what
for(let course in person) {
if(course['cost'] < lowestCostCourse['cost']) {
lowestCostCourse = course;
}
}