我有以下数组
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
}
]
,我希望能够不必说myarray[0].honda || myArray[1].camry
就能访问用户。
有没有办法通过地图功能做到这一点?
答案 0 :(得分:2)
您可以使用map
和Object.values
。
myArrayOfPurchasedCars.map(function (car) { return Object.values(car)[0].user; });
答案 1 :(得分:1)
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);