Hello , I’m start learn javascript objets , I want to know if I can add a new valor and a new key in a objet js and if is yes , how can I do this.
Yes, that’s what objects are for, to store key/value pairs. The FCC JS curriculum goes over how to access and update objects. Are you doing the curriculum?
Yes I do , I try to put a new property color:brown
in this objet:
const ourDog = {
"name :camper,
"leg :5,
tails:2,
}
You have some misplaced quotation marks. Quotation marks only need to be used around a value
that is a string or if the property name contains whitespace. In your example, only camper
needs quotes around it. All other quotation marks should be removed.
Agreed, except the FCC challenges put quotation marks around all keys regardless of whether they really need them. So I can understand why @fchristian97.8 is using them.
can you give me a exemple , ? cause I want to try all that I do in a code editor , please
This challenge gives multiple examples of how to do this. Note how some of the values (numbers) do not have quotes around them and other values that are strings have quotes around them.
Below, I have removed on of the property/value pairs from the first example in the link I provided above for the object named cat
.
const cat = {
"name": "Whiskers",
"tails": 1,
"enemies": ["Water", "Dogs"]
};
So, if I now asked you how to add a property named legs
with a value of 4
to the cat
object, how would you do that? If you look at the first example I reference on that page, you should now understand what adding a property/value pair would look like.
I think that , it will be
const cat = {
"name": "Whiskers",
"tails": 1,
"enemies": ["Water", "Dogs"]
};
cat.leg.push()= 4;
Push is an array method, and cat is not an array. Also that is not how you use push. What you have is not far off, but push is not helping here.
I think it might be helpful to understand that there is no special method for adding key/values to objects. You can literally add a new key/value pair to an object anytime you want with the same syntax you use to get them from an object.
const catName = cat.name;
This gets the value of the key name
from the object cat
. You are accessing the value with simple dot notation. Likewise, you can set the value for a key with dot notation. And the key doesn’t have to exist first. You can create a new key and give it a value at the same time. So if you wanted to set the cat’s name to “Fluffy”, how would you do that using dot notation? If you know that then you also know how to add a new key/value pair to the object.
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.