如何循环和迭代包含objetcs和交换值的Javascript对象

时间:2018-03-31 15:32:53

标签: javascript object

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再做一些事情等等。

3 个答案:

答案 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;
    }
}