Gray Singh
Gray Singh

Reputation: 310

How to Get Keys From Array of Objects and Convert to String

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

Answers (3)

Andy
Andy

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

Siguza
Siguza

Reputation: 23850

Array.prototype.map.

days.map(e => e.id).join(', ')

Upvotes: 1

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

Related Questions