0

I have found this code...

var newEntry, table = [];
newEntry = {
    id: '321',
    price: '1000',
};
table.push(newEntry);
alert(table[0].id);

It works like expected. However I need to add more than one entry, like this...

var newFont, newColor, table = [];
newFont = {
    family: 'arial',
    size: '12',
};
newColor = {
    hex: 'red',
};
table.push(newFont);
table.push(newColor);
alert(table[0].font);

Problem

  • I don't want to write table[0].family.
  • Instead I would like to write table['font'].family.
  • It's a named key instead of just a number. It would be better if the settings increase.
1
  • 1
    Retagged as JavaScript since this is not related to jQuery in any way. It is purely about JavaScript. jQuery is just a JavaScript library. Commented Oct 30, 2013 at 9:00

3 Answers 3

1

It sounds like you want an object, not an array:

var settings = {
    font: {
        family: 'arial',
        size: '12'
    },
    color: {
        hex: 'red'
    }
};
alert(settings.font.family);    // one way to get it
alert(settings['font'].family); // another way to get it
Sign up to request clarification or add additional context in comments.

Comments

0

In JavaScript, arrays can't have named keys, but you can change table to an object and use named keys.

var newFont, newColor, table = {};
newFont = {
    family: 'arial',
    size: '12',
};
newColor = {
    hex: 'red',
};

table.font = newFont;
table.color = newColor;

console.log(table['font'].family);
console.log(table.font.family);

4 Comments

"In JavaScript, arrays can't have named keys" Yes, they can. Standard JavaScript arrays aren't really arrays at all, they're just objects with some special behavior. var a = []; a.foo = "bar"; console.log(a.foo); will show you "bar".
well what you're saying is true and I agree but in practice you would distinguish between objects and arrays, only using an array if fit for purpose. I probably should have said arrays shouldn't have named keys in the context of what OP wants.
I add named keys to arrays all the time. For instance, if I want something that's ordered but I also want to look up entries by a key property, I'll usually do a = []; a.index = {}; and then add the objects to the array and the index (using the key). It's fine provided you don't expect it to survive a round trip through JSON, since JSON's arrays don't have a notation for this.
Looks like we could debate this for some time. Thanks for the comments, cheers
0

Did you try this : table['font'] = newFont; ?

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.