0

I have a code that makes a variable object list but if I want to change one of the values for one of the keys I can't, can someone help me with this issue?

I'm using bootstrap and jquery/javascript to try to get it to work

let keyholders = [{}];

function addPerson(){
   var name = document.getElementById('name').value;
   var addNameSelect = '';
   let id = keyholders.length;
    var newHolder = {
    [name]:{
        "id": id,
        "keys": {
          "garage": false,
          "frontdoor": false,
          "balcony": false,
        },
      },
    };
    keyholders.push(newHolder);
}
<input class="form-control" placeholder="NAME" type="text" name="name" id="name">
<button class="btn btn-outline-secondary" onclick="addPerson()" type="button" id="personadd">ADD</button>

Ive tried to use:

var holder = document.getElementById('name').value;
keyholders.holder.keys.garage = true;

but my console says .holder is not a function

Not A Bot
  • 2,474
  • 2
  • 16
  • 33

2 Answers2

0

You should write like this,

let index = keyholders.findIndex(item => Object.keys(item).includes(holder));
if(index > -1) {
    keyholders[index][holder].keys.garage = true;
 }

Because keyholders is an array and you should access by index and inside that index you should access using the holder variable.

Md Sabbir Alam
  • 4,937
  • 3
  • 15
  • 30
0

The main issue is because there is no holder property in the object. You need to access the object using array notation so that the value of holder is used as the key, not the literal work 'holder':

keyholders[holder]keys.garage = true;

However this raises a second issue due to the use of an array of objects - the holder key is not in the array, but the child object. As such without knowing the index of the object to find within you cannot retrieve the holder - and if you knew the index anyway, you wouldn't need to use holder at all.

As such it makes far more sense to just use a single object whose properties match the values entered in to the #name box. Try this:

let keyholders = {};

function addPerson() {
  var name = document.getElementById('name').value;
  var addNameSelect = '';
  let id = keyholders.length;

  keyholders[name] = {
    "id": id,
    "keys": {
      "garage": false,
      "frontdoor": false,
      "balcony": false,
    }
  };
  console.log('added');
}

document.querySelector('.set').addEventListener('click', () => {
  var name = document.querySelector('#name').value;
  keyholders[name].keys.garage = true;
  console.log(keyholders);
});
<input class="form-control" placeholder="NAME" type="text" name="name" id="name" value="foo">
<button class="btn btn-outline-secondary" onclick="addPerson()" type="button" id="personadd">ADD</button>

<button class="set">Set garage keys = true</button>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339