Jens Törnell
Jens Törnell

Reputation: 171

array object with named key

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

Upvotes: 0

Views: 111

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1074258

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

Upvotes: 1

Mirza Selimovic
Mirza Selimovic

Reputation: 1739

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

Upvotes: 0

MrCode
MrCode

Reputation: 64526

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);

Upvotes: 0

Related Questions