0

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"

3 Answers 3

1

Array.prototype.map.

days.map(e => e.id).join(', ')
Sign up to request clarification or add additional context in comments.

Comments

0

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')  )

Comments

0

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));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.