Reputation: 310
I have an array of objects called days
and I need to get the id
of it and combine into one string separated by a comma.
let days = [
{
"id": "Fri",
"name": "Friday"
},
{
"id": "Wed",
"name": "Wednesday"
}
]
CODE
let days = Object.keys(days).join(',');
EXPECTED OUTPUT
"Wed, Fri"
Upvotes: 0
Views: 1413
Reputation: 63524
map
over the objects in the array to get an array of ids, sort
it to get the correct order of elements, and then join
that array into a string.
let days=[{id:"Fri",name:"Friday"},{id:"Wed",name:"Wednesday"}];
const out = days
.map(obj => obj.id)
.sort((a, b) => a.localeCompare(b) < b.localeCompare(a))
.join(', ');
console.log(out);
// If you want those double quotes too
console.log(JSON.stringify(out));
Upvotes: 0
Reputation: 11
For this, you have to loop through the array first.
let data = [
{
"id": "Fri",
"name": "Friday"
},
{
"id": "Wed",
"name": "Wednesday"
}
]
function filterData(key) {
let days = []
data.forEach((item, index) => {
days.push(item[key])
})
return days.join(',');
}
console.log( filterData('id') )
console.log( filterData('name') )
Upvotes: 0