How useful are Built-in object methods?

Question

How useful are Built-in object methods?

Answer

Very!
Let’s say we have an object that we want to make it into a drop-down menu. this will be a visual of what we have:

const objForMenu = {
  length: [100, 200, 300, 400],
  size: [20, 25, 30, 35, 40],
  weight: [110, 120, 130, 140, 150, 160, 170, 180, 190, 200],
  age: [18, 19, 20 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
}

so if we want to make a dropdown for keys and for values we could get the first ones with object.keys() and loop through them:
(we will be imagining that we already have the HTML unordered list on a variable list)

Object.keys(objForMenu).forEach(key => {
  let li = document.createElement('li');
  li.innerHTML = key;
  list.appendChild(li);
})

and now, lets check for the second dropdown, let’s say we have a variable selected that stores the selection from the previous menu and we have another list already assigned to a secondList variable, we could use object.entries():

Object.entries(objForMenu).forEach((entry) => {
  if(selected === entry[0]){ 
//remember that .entries creates an array of arrays, so the first element of each inner array is the key
    entry[1].forEach(value => {
      let li = document.createElement('li');
      li.innerHTML = value;
      secondList.appendChild(li);
    }}
  }
})

So there we used .entries() to be able to have key and values in pairs, that made it easier for us to check if the selection from the first dropdown (saved in our selected variable) is the same as one of the keys, when we find the matching key, we grab the corresponding array value and loop though it to build our second dropdown.

there are many other useful ways for why you might want to use built-in object methods, but at least this will give you an idea for them.

11 Likes

Hey guys!

I have a question regarding the Object.assign() method.

In the exercise on built-in object methods (https://www.codecademy.com/courses/introduction-to-javascript/lessons/advanced-objects/exercises/object-methods), we are asked to create a new object called newRobot that corresponds to the robot object with additional new keys without mutating the robot object itself.

In order to do so, I created a new object called addedFeatures that would later be combined to robot.

//initial object
const robot = {
	model: 'SAL-1000',
  mobile: true,
  sentient: false,
  armor: 'Steel-plated',
  energyLevel: 75
};

//object containing the new keys
const addedFeatures = {
  laserBlaster: true,
  voiceRecognition: true
};

const newRobot = Object.assign(addedFeatures, robot);

In this context, I have indeed created newRobot that contains both robot and addedFeatures objects without mutating the robot object. However, addedFeature has now been mutatuted which means that if I wanted to add it to another object, it would be exactly the same as adding the new variable newRobot. In order to avoid this, I thought about creating an extra empty object that would be the target for the Object.assign() method.

const newBot = {};

const newRobot = Object.assign(newBot, robot, addFeatures);

By doing so, I create an object that has no other purpose than being the target for the method and thus, while sparing the two initial object, I still end up again with twice the same object. I was wondering whether there was another option, where I would be able to create a new object by combining two others without affecting any of the objects I combine nor creating an extra “useless” object.

Thanks for the help guys!

4 Likes

Hey! I’m sure I’m not the best person to help you, but I saw you hadn’t gotten an answer yet and just wanted to say I did this:

const newRobot = Object.assign({ laserBlaster: true, voiceRecognition: true }, robot);

I can’t say if it’s best practice, but it worked! :grin:

4 Likes

Hey! Thanks for the answer.
That’s indeed another way to do it. I’ll keep it in mind.
That would mean writing (or copy/paste) the entire object each time I would need it, though.

1 Like

I did like this and it worked too:

const newRobot = Object.assign({ }, robot, addFeatures);

6 Likes

Hey pyrunner49398!

Thanks for your answer! This would definitely solve the problem I had!
Instead of creating an extra object, I could have added the two objects to an empty one directly within the method.
I like this one!

1 Like

Hi Guys, I couldnt find a reson why the order of the inherited / copied properties and the new proerties assigned was such as it is…

The task described was:
" we want another object that has the properties of robot but with a few additional properties." &" Declare a const variable named newRobot . newRobot will be a new object that has all the properties of robot and the properties in the following object: {laserBlaster: true, voiceRecognition: true} . Make sure that you are not changing the robot object!"

For some reason
This works:
// Declare newRobot below this line:

const newRobot = Object.assign({laserBlaster: true, voiceRecognition: true}, robot);

But this fails:
// Declare newRobot below this line:

const newRobot = Object.assign(robot, {laserBlaster: true, voiceRecognition: true});

Why does the order matter, it wasnt clear to me from the example documentation either…
Thanks in advance

1 Like

Hi, this is my observation:
By definition from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign.
Its syntax is: Object.assign(target, …sources)
When you declare:
const newRobot = Object.assign(robot, {laserBlaster: true, voiceRecognition: true});
‘robot’ object becomes target as it’s the first order of the assigned objects. Console.log(robot) gives the result:

  1. armor: “Steel-plated”
  2. energyLevel: 75
  3. laserBlaster: true
  4. mobile: true
  5. model: “SAL-1000”
  6. sentient: false
  7. voiceRecognition: true
    (ignore the numbers as I copied and pasted from Google Developer pad, and note that properties of an object have no order).
    But this does not satisfy the condition given in the assignment, ’ Make sure that you are not changing the robot object!’ as stated at the end.

Nevertheless, Console.log(newRobot) also gives the correct result which is the original robot’s properties/methods plus the two new methods by your ‘style’ so I can’t really say it ‘fails’!

4 Likes

Hi everyone!
i was reading the MDN documentation and i was wondering about the difference between “object instance methods” and “Object class methods” ?
can anyone explain it to me ?
Thanks to who will help!

Thank you for your posts it is interesting to see that there are many ways to do this.
My solution was this and also worked:

const newRobot = {laserBlaster: true, voiceRecognition: true};
Object.assign(newRobot, robot);*/
console.log(newRobot);

Although newRobot was declared using const, and not usually mutable such as when declared using let or var, the properties themselves are still free to be changed as was discussed in the Objects lesson earlier. So, creating an additional object isn’t necessary as the newRobot object, alone can be updated, at least as afar as it’s properties are concerned.

4 Likes

I don’t think you’d normally want to store the return value of Object.assign() to a variable. Once you’ve mutated the object, it’s mutated! No need to store the same object in a new variable (unless you actually need to). I think Codecademy only wanted us to try this out for us to know what the return value of Object.assign() is

With ES2018, it seems we may take advantage of the spread operator with object literals:

const newRobot = {...robot, ...addedFeatures}

This way, neither robot nor addedFeatures will be mutated and thus can be re-used.
ref: Spread syntax (...) - JavaScript | MDN

1 Like

Am I supposed to understand the HTML references in this example? I don’t think the course has showed us how use data from an HTML document yet.

That part is what frustrated me at the the whole exercise, because I didn’t know we are allowed to stock in new properties like that in a method call. It looks messy and I declared 2 variables separately, to which the example gave it wrong to me. Not to mention, the documentation they provided doesn’t show an example like this, but one in which the properties are already declared in a new variable. I also thought you cannot declare new properties in the method call, if they are not declared into a variable name first. Why does it work this way? :frowning:

1 Like
let newProperties = {prop1, prop2};
const newRobot = Object.assign(newProperties, robot);

is equivalent to

const newRobot = Object.assign({prop1,prop2}, robot);

because in order to execute the code, the variable name needs to be substituted with the content of the variable before the function’s logic can be applied. It’s similar to how you would evaluate a mathematical function, like in this middle/high school flashback:

let x = 2 and y = 3, 
evaluate f(x) = x^2 + 4xy + y^3

Your first step will generally be to rewrite the function with all the variables substituted for their values (x->2 and y->3, here), then work on applying the function’s logic. Same goes for code functions/methods.

So while

const newRobot = Object.assign({prop1,prop2}, robot);

can and does work, it’s not ideal. If you ever want to change another object with the same set of newProperties you’d need to write them all out again instead of just being able to just re-use newProperties (though this example is flawed for that because newProperties does get modified by Object.assign, check this forum thread for ways to get around that), and it makes your code messier and easier to mess up (because more keystrokes).

After reading Object.assign() MDN this is what I understood…

const robot = { model: 'SAL-1000', mobile: true, sentient: false, armor: 'Steel-plated', energyLevel: 75 }; // What is missing in the following method call? const robotKeys = Object.keys(robot); console.log(robotKeys); // Declare robotEntries below this line: const robotEntries = Object.entries(robot); console.log(robotEntries); // Declare newRobot below this line: const newRobot = {LaserBlaster: true, voiceRecognition: true}; const returnednewRobot = Object.assign(newRobot, robot); console.log(newRobot);

const newRobot = {LaserBlaster: true, voiceRecognition: true};

const returnednewRobot = Object.assign(newRobot, robot);

console.log(newRobot);

This stiil had the same outcome as what the Solution logged

:thinking:

Is this still Correct?

Hello,

You could do this way, and maintain the same “robot” properties plus the new ones, instead of putting the new ones on top of the “robot” ones.

const robot = { model: 'SAL-1000', mobile: true, sentient: false, armor: 'Steel-plated', energyLevel: 75 }; const newRobot = Object.assign({}, robot, {laserBlaster: true, voiceRecognition: true}); console.log(newRobot);