Reputation: 895
There is an object and i want to access it and
show 'my name is Rudolf the raindeer'
Here is the object:
let obj = {
my: 'name',
is: 'Rudolf',
the: 'raindeer'
}
What I try in my JS:
Object.entries(obj).map(value=>{
console.log("My"+value[1]+"is"+value[2]+"the"+value[3]);
})
How do i access the object right to get the value?
Upvotes: 0
Views: 74
Reputation: 822
Simple solution which uses a for in loop. For in loops are your friend when it comes to working with objects.
let obj = {my: 'name', is: 'Rudolf', the: 'raindeer'}
var sentence = '';
for(var char in obj){
sentence += char + ' ' + obj[char] + ' ';
}
console.log(sentence)
In the for in loop above, char represents the key name (my, is, the) and obj[char] gives you the value for they key name ('name', 'Rudolf', 'raindeer'). Combine them together to build up the sentence.
Hope this helps.
Upvotes: 0
Reputation: 370679
Join each entry by spaces, then join all the entries by spaces too:
let obj = {
my: 'name',
is: 'Rudolf',
the: 'raindeer'
}
const str = Object.entries(obj)
.map(entry => entry.join(' '))
.join(' ');
console.log(str);
In newer browsers (or with a polyfill) you could .flat
:
let obj = {
my: 'name',
is: 'Rudolf',
the: 'raindeer'
}
const str = Object.entries(obj).flat().join(' ');
console.log(str);
Also, only use .map
when you want to create a new array from each element of the array you're iterating over - for generic iteration, better to use forEach
.
Upvotes: 1