0

I have an empty array for example called const arr = []; and when I click the button in page I want to create new Object inside this array, I do that with this following code line


//add is button element
const add = document.querySelector(".add");

//value is input element
const valueInput = document.querySelector(".value");

add.addEventListener('click', ()=> {
    arr.push(new Object)
    console.log(arr)
})

it makes object but I want to grab this Object and insert inside new property for example to called "text" and array should look like that

arr[{text: ''}]

and every click I want to create new object in this array and property still must be text, inside the text I will put input value

I tried on my own

arr.push(new Object = {text})
arr.Object.text = valueInput.value

but both of them give me left-hand error

callmenikk
  • 1,358
  • 2
  • 9
  • 24
  • 2
    Familiarize yourself with [how to access and process nested objects, arrays or JSON](/q/11922383/4642212) and how to [create objects](//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer). `{text: valueInput.value}` is the object you want to push. Have you tried pushing that instead of `new Object`? `new Object = {text}` is invalid syntax. `arr.Object.text = valueInput.value` doesn’t make sense because your array doesn’t have an `Object` property. – Sebastian Simon May 31 '21 at 13:08
  • you can use object literal also `arr.push({})` – DecPK May 31 '21 at 13:09
  • you are welcome, you can use @ + username to mention someone. If you only type the username, they cannot be notified. – ikhvjs May 31 '21 at 13:17

1 Answers1

1

Just use the object literal with a property text and its value would be valueInput.value.

//add is button element
const add = document.querySelector(".add");

//value is input element
const valueInput = document.querySelector(".value");

const arr = [];
add.addEventListener("click", () => {
  arr.push({
    text: valueInput.value
  });
  console.log(arr);
});
<input type="text" placeholder="Insert text" class="value" />
<button class="add">add</button>
DecPK
  • 24,537
  • 6
  • 26
  • 42