0

I'm trying to create an multidimensional and associative array. I'm tried a PHP-like syntax but it doesn't work. How to solve?

var var_s = ["books", "films"];
var_s["books"]["book1"] = "good";
var_s["books"]["book2"] = "bad";
var_s["films"]["films1"] = "bad";
var_s["films"]["films2"] = "bad";
asked Jan 15, 2016 at 11:18
2

3 Answers 3

1

Use objects:

var var_s = {"books":{}, "films": {}};
var_s["books"]["book1"] = "good";
-> {books: {book1: "good"}, films: {}}
answered Jan 15, 2016 at 11:22
Sign up to request clarification or add additional context in comments.

Comments

0

You want object literal syntax:

var_s = {
 books: {
 book1: "good",
 book2: "bad"
 },
 films: {
 film1: "good",
 film2: "bad"
 }
}

Retrieving a value:

var myBook = var_s.books.book1

Setting:

var_s.books.book3 = "terrible"

I recommend reading You Don't Know JS for a good crash course in JS basics. Chapter 2 of Book 1 specifically covers objects and initialization,

answered Jan 15, 2016 at 11:22

Comments

0

You could use objects,

var Book = {
 'bookOne': 'good',
 'bookTwo': 'bad' 
};
/** Output => good **/
console.log(Book.bookOne);

Note: If you need, you can put an array within the object.

Reading Material

Working with Objects

answered Jan 15, 2016 at 11:23

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.