Student Swap - Swapping JavaScript Object Values Explained
In JavaScript, objects are made up of primatives such as string & number which contain values. Assigning a JavaScript object to a variable like in the following statement assigns the memory address of the object to the variable student.
const student = { name: "Max", age: 22}
If we wanted to create a copy of this object, we would have to use the ES6 spread operator ... to extract the properties of the object and wrap inside curly brackets to create a new object based on the extracted properties.
const studentTwo = {...student}
Check back here to read more about ES6 syntax for JavaScript when I publish more blog posts.
Now, if we wanted to swap the values of two JavaScript objects, I would first have to create a copy of one object, assign this to a temporary variable, create a copy of the other object and assign it to the copied object. Then, you set the second variable you copied to the temporary variable (memory address).
Solution
// Updating key/value pairs of objects
let students = {
jacob: {
classes: ["math", "chemistry", "english"],
grade: 11,
age: 16,
},
guillermo: {
classes: ["history", "math", "physics"],
grade: 12,
age: 17,
},
};
// Write your solution here
// Hint: Use the 'temp' variable to hold on to one value while you swap it for the other.
let temp= {
};
temp.jacob = {...students.jacob}
students.jacob = {...students.guillermo}
students.guillermo = {...temp.jacob}
// DO NOT MODIFY CODE BELOW
// This will test your code solution
require('./test.js'); void 0;