Home > Software engineering >  Javascript: object with array of objects
Javascript: object with array of objects

Time:03-16

I'm fighting with some JSON and met situation similar to something below:

let build = '{"books": [{"title":"Something", "pages": 154, "illustrations":false},{"title":"Blabla", "pages": 356, "illustrations":true},{"title":"nope", "pages": 700, "illustrations":false}] }'

let books = JSON.parse(build);
console.log(books)

I can't find a way to reach data inside this 'Book' object. Could you give me some hint?

CodePudding user response:

What you provided seems to work, then you can access data inside it, just as you would to in a literal object in javascript:

let build = '{"books": [{"title":"Something", "pages": 154, "illustrations":false},{"title":"Blabla", "pages": 356, "illustrations":true},{"title":"nope", "pages": 700, "illustrations":false}] }'

let data = JSON.parse(build);
console.log(data.books[0].title)

I think you got confused by the variable name you chose: JSON.parse will not go to the books key by itself, because there could be other keys

CodePudding user response:

books.books[0]

should show the next : {title: 'Something', pages: 154, illustrations: false}

or if you prefer you can iterate in the next way

books.books.forEach (element => console.log(element))

CodePudding user response:

Just use . operator to access properties, and the array access operator [] or some kind of iteration to access the array elements.

const build = '{"books": [{"title":"Something", "pages": 154, "illustrations":false},{"title":"Blabla", "pages": 356, "illustrations":true},{"title":"nope", "pages": 700, "illustrations":false}] }'

// convert JSON to object
const data = JSON.parse(build);
// Pull out the 'books' property from the root level object
const books = data.books;
// see what it looks like
console.log(books);

// Define a function that will iterate the books and print some info about the book
const printAllTitles = (books) => {
  books.forEach(book => {
    console.log(`${book.title} is ${book.pages} pages long`)
  })
}

// Call that function
printAllTitles(books);
  • Related