mnickey mnickey - 1 month ago 5
Javascript Question

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

Answer

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

Comments