Arex Speed
Arex Speed

Reputation: 177

Add new object in array

It seems easy but it is not working for me. I want o add new array and name in object after fill input. When clicking at button OK should add new object. For example:

let arr = [{
    name: 'thomas',
    point: ''
  },
  {
    name: 'this should be value from input',
    point: ''
  }];

Now I have this code:

Name: <input type="text" id="input">
<button onclick="ok()">OK</button>

const input = document.querySelector('#input');

const arr = [{
    name: 'Thomas',
    point: ''
  }];
function ok(){


arr['name'].push(input.value);
console.log(input.value);
console.log(arr);
}

Upvotes: 0

Views: 49

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074058

You need to create a new object, and callpush on the array, not the object inside it:

    arr.push(
// −^^^^^^^^
        {                         // This part is an "object
            name: input.value,    // literal" that creates
            point: ''             // a new object with these
        }                         // properties in it
    );

Upvotes: 2

Related Questions