Igniter
Igniter

Reputation: 887

How to get known properties of an object nested in another object?

Keys of books object are automatically generated by Firebase.

{
  books: {
    -LKsSspLai8tTppJjSiE: {
      author: 'Author 1',
      name: 'Book 1'
    },
    -LKsS15TMhGRQXlZZlkE: {
      author: 'Author 2',
      name: 'Book 2'
    },
    {}, {}...
  }
  timestamp: 1535579350
}

I have no problem with accessing first level properties, but how can I create an array from books object for further looping over authors and names?

Upvotes: 1

Views: 55

Answers (2)

Javid Jamae
Javid Jamae

Reputation: 9009

If you want to convert an object's values into an array (as you asked), you could use lodash:

const a = {
  books: {
    "-LKsSspLai8tTppJjSiE": {
      author: 'Author 1',
      name: 'Book 1'
    },
    "-LKsS15TMhGRQXlZZlkE": {
      author: 'Author 2',
      name: 'Book 2'
    },
  },
  timestamp: 1535579350
}

console.log( _.values(a.books) )
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>

Upvotes: 0

TheVirtuoid
TheVirtuoid

Reputation: 100

You can use Object.values(books), then loop through that array.

Object.values(books).forEach( (book) => {
    // now you have book.author and book.name
});

Upvotes: 2

Related Questions