0

I am creating simple App using Vanilla JavaScript, I have some issue, Let's explain my problem,In the beginning i have empty array, I want to push some values from Input field, and it's works fine, but i want to push only one object into arrOfObj:[], that means i want replace old value by new value, without changing the length.

var arrOfObj = [];
function pushObject() {
  var inputVal = document.getElementById('mainInput').value;
  arrOfObj.push({ id: 1, value: inputVal });
  console.log(arrOfObj);
}
<button onclick="pushObject()">click</button>
<input type="text" id="mainInput">

4
  • If I am getting this right you need arrObj to contain the most recent value of text input before click is pressed? Commented Dec 25, 2020 at 11:32
  • 2
    why not arrOfObj[0] = {'id':1, 'value':inputVal}? Commented Dec 25, 2020 at 11:33
  • @stark Exactly i want to update always firs value Commented Dec 25, 2020 at 11:36
  • 2
    Then why have a list arrObj why not update single object? Commented Dec 25, 2020 at 11:40

2 Answers 2

1

I think instead of using push, you can directly replace the first index with your new object

    var arrOfObj = [];
    function pushObject(){
     var inputVal = document.getElementById('mainInput').value
     //replace the first value of array
     arrOfObj[0] = {'id':1, 'value':inputVal};
      console.log(arrOfObj)
    }

    
    <button onclick="pushObject()">click</button>
    <input type="text" id="mainInput">
Sign up to request clarification or add additional context in comments.

1 Comment

You got to update the function name to something like "updateObject" too then
0

You can achieve this by simply updating the 0th element of your array if there is one.

var arrOfObj = [];
function pushObject(){
  var inputVal = document.getElementById('mainInput').value
  if (arrOfObj[0]) {
    arrOfObj[0].value = inputVal
  } else {
    arrOfObj.push({'id':1, 'value':inputVal})
  }
  console.log(arrOfObj)
}
<button onclick="pushObject()">click</button>
<input type="text" id="mainInput">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.