68

I've tried looking to see if this is possible, but I can't find my answer.

I'm trying to get the following to work:

var defaults = {
 'background-color': '#000',
 color: '#fff',
 weekdays: {['sun','mon','tue','wed','thu','fri','sat']}
};

It just gives an error, and I've tried using ({...}) and [{...}] I'd like to be able to access the weekdays using something like:

defaults.weekdays[0];

is this possible?

3
  • 6
    You're not mentioning this, and no one has commented on it yet, but if you want a hyphen in a key like background-color, it needs to be quoted. Eg "background-color": '#000' Commented Dec 1, 2009 at 21:11
  • 8
    Quick note: [] is for arrays, {} is for objects Commented Dec 1, 2009 at 21:13
  • Thanks CresentFresh, I added the quotes, but it wasn't the problem I was running into :) Commented Dec 1, 2009 at 23:43

7 Answers 7

126

Kill the braces.

var defaults = {
 backgroundcolor: '#000',
 color: '#fff',
 weekdays: ['sun','mon','tue','wed','thu','fri','sat']
};
Sign up to request clarification or add additional context in comments.

9 Comments

Also make sure that you don't have a trailing comma after the end of the final ], or your code will break in IE7.
Really? I've only seen breakage in IE7, and I see it every time I refactor. Every single time. Perhaps IE6's behavior is nondeterministic. That's worse than failing every time, right?
I get "missing : after property id"
This works for me, as long as you put quotes around "background-color", as Crescent Fresh mentioned above.
Don't use the dash, or use quotes as mentioned.
|
13
// define
var foo = {
  bar: ['foo', 'bar', 'baz']
};

// access
foo.bar[2]; // will give you 'baz'

1 Comment

Can you do like var foo = { bar: [] } and then say foo.bar[7] = 'hi'; like you can when its outside of an object?
5

var data = {
  name: "Ankit",
  age: 24,
  workingDay: ["Mon", "Tue", "Wed", "Thu", "Fri"]
};

for (const key in data) {
  if (data.hasOwnProperty(key)) {
    const element = data[key];
      console.log(key+": ", element);
  }
}

Comments

5

If you are so organised you may declare the entire object from the outset (this comma-delimited list is called an object initializer):

const myObject = {
    string:     'Galactic Rainbows',
    color:      'HotPink',
    sociopaths: [ "Hitler", "Stalin", "Gates" ]
}

Alternatively, once you have declared the object,

  // this line is the declaration:
const myObject = {};  
  // it is equivalent to:
const myObject2 = new Object();

you may define its properties by giving them values:

myObject.string     = "Galactic Rainbows";
myObject.color      = "HotPink";
myObject.sociopaths = [ "Hitler", "Stalin", "Gates" ];
     //  ^properties  ^values        

All examples below assume the object is already declared (as above)

I prefer to declare the array separately, like this, and then assign it to the object:

const weekdays    = [ 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ];
myObject.weekdays = weekdays;
myObject.weekdays[0] 
               // => 'sun'

But if you have already declared the object, it would be quicker to code:

myObject.weekdays = [ 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ];

But you cannot assign an array of arrays to the object like this:

myObject.girlsAndBoys[0] = [ "John", "Frank", "Tom"   ];   //Uncaught TypeError: Cannot set property '1' of undefined
myObject.girtsAndBoys[1] = [ "Jill", "Sarah", "Sally" ];   //Uncaught TypeError: Cannot set property '1' of undefined

To assign a two dimensional array to an object you have a few options. You can initialise the empty 2D array first:

myObject.girlsAndBoys    = [[]];
myObject.girlsAndBoys[0] = [ "John", "Frank", "Tom"   ]; 
myObject.girtsAndBoys[1] = [ "Jill", "Sarah", "Sally" ];   

Or you may do it layer by layer:

const boys            = [ "John", "Frank", "Tom"   ];    
const girls           = [ "Jill", "Sarah", "Sally" ];
myObject.girlsAndBoys = [[ boys ],[ girls ]];

Alternatively you may do it all at once (after no more than the object declaration):

const myObject              = {};
myObject.girlsAndBoys       = [[ "John", "Frank", "Tom"   ],
                               [ "Jill", "Sarah", "Sally" ]];
myObject.girlsAndBoys[0][0] == "John";   // returns True

Comments

1

var defaults = {

  "background-color": "#000",
  color: "#fff",
  weekdays: [
    {0: 'sun'},
    {1: 'mon'},
    {2: 'tue'},
    {3: 'wed'},
    {4: 'thu'},
    {5: 'fri'},
    {6: 'sat'}
  ]

};
               
console.log(defaults.weekdays[3]);

Comments

0
var obj = {
 webSiteName: 'StackOverFlow',
 find: 'anything',
 onDays: ['sun'     // Object "obj" contains array "onDays" 
            ,'mon',
            'tue',
            'wed',
            'thu',
            'fri',
            'sat',
             {name : "jack", age : 34},
              // array "onDays"contains array object "manyNames"
             {manyNames : ["Narayan", "Payal", "Suraj"]}, //                 
           ]
};

Comments

0

In regards to multiple arrays in an object. For instance, you want to record modules for different courses

var course = {
    InfoTech:["Information Systems","Internet Programming","Software Eng"],
    BusComm:["Commercial Law","Accounting","Financial Mng"],
    Tourism:["Travel Destination","Travel Services","Customer Mng"]
};
console.log(course.Tourism[1]);
console.log(course.BusComm);
console.log(course.InfoTech);

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.