I'm new to Javascript and I have an object that printed to console gives this :
Object
mots[4]:"unique"
I would like to edit it to get :
Object
mots[4].lettre:"unique"
I tried using stringify, split and splice but that didn't work. So what is the 'cleanest' way to do that?
mots[4] = { lettre : "unique" }
or generically..
mots[i] = { lettre : mots[i] }
or for each value in the array you can do..
mots = mots.map(function(x) { return { lettre : x }; });
This will convert every element of the array to be an object with the property lettre with the value of the original element. Learn more about the map function .
var mots = ['This', 'answer', 'is', 'very', 'unique']; console.log('Before:'); console.log(mots); console.log('mots[4] : ' + mots[4]); mots = mots.map(function(x) { return { lettre : x }; }); console.log('After:'); console.log(mots); console.log('mots[4].lettre : ' + mots[4].lettre);
You have to assign to it an object.
var a=4;
mots[a]={letter:"unique"};
You can access it using bracket
notation.
console.log(mots[a]["lettre"]).
var mots=[]; for(i=0;i<5;i++){ mots[i]=i; } a=4; console.log(mots); mots[a]={letter:"unique"}; console.log(mots[a]["letter"]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.