Reputation: 83
I have following array
const myArrayOfPurchasedCars = [{
honda: {
user: 'et',
links: {
img: {
href: 'some0imghere'
},
year: 2010
},
{
camry: {
user: 'st',
links: {
img: {
href: 'some0imghere'
},
year: 2014
},
{
maxima: {
user: 'lt',
links: {
img: {
href: 'some0imghere'
},
year: 2015
},
{
optima: {
user: 'it',
links: {
img: {
href: 'some0imghere'
},
year: 2018
}
]
and I want to be able to access the user without having to say myarray[0].honda || myArray[1].camry
.
Is there a way to do that with a map function?
Upvotes: 0
Views: 65
Reputation: 581
You can use map
and Object.values
.
myArrayOfPurchasedCars.map(function (car) { return Object.values(car)[0].user; });
Upvotes: 2
Reputation: 21658
const myArrayOfPurchasedCars = [
{
honda: {
user: 'et',
links: {
img: {
href: 'some0imghere'
},
year: 2010
}
}
},
{
camry: {
user: 'st',
links: {
img: {
href: 'some0imghere'
},
year: 2014
}
}
},
{
maxima: {
user: 'lt',
links: {
img: {
href: 'some0imghere'
},
year: 2015
}
}
},
{
optima: {
user: 'it',
links: {
img: {
href: 'some0imghere'
},
year: 2018
}
}
}
];
const users = myArrayOfPurchasedCars.map(car => Object.getOwnPropertyNames(car).map(p => car[p].user)[0]);
console.log(users);
Upvotes: 1