通过具有不同键的对象数组进行映射

时间:2018-10-11 05:28:55

标签: javascript iteration

我有以下数组

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就能访问用户。

有没有办法通过地图功能做到这一点?

2 个答案:

答案 0 :(得分:2)

您可以使用mapObject.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);