mnickey
mnickey

Reputation: 787

Adding properties to an array in javascript

I have an object that contains an array. While the items push through, what I am trying to do is set each item upon creation to have a checked value of False. Currently, I am seeing that this is setting the entire array to have a value of false. How can I modify this to have each item it's own checked value?

Desired output of items:

["a", "checked": False], ["aa", "checked": False], ["aaa", "checked": False]

// state objects
var state = {
    items: []
};

// state modification functions
function addItem(state, item) {
    item.name = item;
    state.items[item["checked"]] = "False";
    state.items.push(item);
    console.log(state.items);
}

Upvotes: 0

Views: 54

Answers (2)

Rafal
Rafal

Reputation: 573

Some time easier is witch object

[{name: "a", checked: false}, {name: "aa", checked: false}]

// state objects
var state = {
    items: []
};

// state modification functions
function addItem(item) {
    state.items.push(item);
}

addItem({name: "a", checked: false})

Upvotes: 0

salezica
salezica

Reputation: 76899

What you want is an Array that contains Objects. Try this:

function addItem(state, item) {
    state.items.push({
      name   : item,
      checked: false
    })
}

You can then access state.items[0] to get the { name, checked } object, or state.items[0].name/state.items[0].checked directly

Upvotes: 3

Related Questions