I have an array of objects in Javascript and I want to collect just the given key and value from the list. How would one do this? I feel like I have over engineered the solution but maybe not.
I wasn't sure if there was a cleaner way of doing this.
The results should be a list of objects containing just the key 'id' and id 'value'.
const items = [{
id: "45054",
name: "Brittany"
},
{
id: "8980",
name: "Amber"
},
{
id: "9843",
name: "Leslie"
},
{
id: "45306",
name: "Doug"
},
{
id: "7863",
name: "Kevin"
},
]
let ids = []
for (let i = 0; i < items.length; i++) {
ids.push({
id: items[i].id
})
}
console.log(ids)
that isn't bad, I personally would just use map:
let ids = items.map(item => ({id: item.id}));
A cleaner way would be using Array.prototype.map(). Your answer is certainly not a wrong way to do so, though.
const items = [{
id: "45054",
name: "Brittany"
},
{
id: "8980",
name: "Amber"
},
{
id: "9843",
name: "Leslie"
},
{
id: "45306",
name: "Doug"
},
{
id: "7863",
name: "Kevin"
},
]
const ids = items.map(x => ({id: x.id}));
console.log(ids)
To deal with this you can use map like Pranev said, but if you want to have a more specific solution based on any other key, you can play with Object.keys, and then use the key that you want to get the id or any other key.
const items = [
{
id: "45054",
name: "Brittany",
},
{
id: "8980",
name: "Amber",
},
{
id: "9843",
name: "Leslie",
},
{
id: "45306",
name: "Doug",
},
{
id: "7863",
name: "Kevin",
},
];
let ids = [];
for (let i = 0; i < items.length; i++) {
const keys = Object.keys(items[i]);
keys.forEach((key) => {
if (key === "id") {
ids.push({
id: items[i][key],
});
}
});
}
console.log(ids);