0

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?

3
  • What are the "users"? Commented Oct 11, 2018 at 5:33
  • Your data format seems to be incorrect due to missing closing brackets. Also do you want to get all users in the data Commented Oct 11, 2018 at 5:33
  • Are you intentionally nesting maxima inside of camry inside of honda inside of etc.? Commented Oct 11, 2018 at 5:35

2 Answers 2

2

You can use map and Object.values.

myArrayOfPurchasedCars.map(function (car) { return Object.values(car)[0].user; });

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.