简体   繁体   English

如何循环和遍历包含objetcs和交换值的Javascript对象

[英]How to loop and iterate over Javascript objects containing objetcs and swap values

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"} 
        };

Can anyone please show how to loop and iterate through this person object and swap the course1 and course2 object values(name, day, time) and do something, replace it and swap course1 and course3 again do something and so on... 任何人都可以显示如何循环和遍历此person对象并交换course1和course2对象的值(名称,日期,时间)并执行某些操作,替换它并再次交换course1和course3进行操作等等吗?

You can use Object.keys in order to get all an array of keys, and then you can iterate over it. 您可以使用Object.keys来获取所有键数组,然后可以对其进行迭代。

Something like that: 像这样:

 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... }); 

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);

You want to compare with course1 on each iteration, so it doesn't make sense to use the key in forEach . 您希望在每次迭代时都与course1进行比较,因此在forEach使用键没有任何意义。

// 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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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