Search code examples
arraysobjectprompt

Javascript How do i edit and update an object


New to javascript! What if I want to edit and update an object with pre-existed value?

array [];

// this function is for pre-existed value
function object1 ( mytext ) {
this.text = mytext
}

var usertext = new object ("my text to edit");
memArray.push (usertext);
console.log (usertext)

What about edit/update for prompt value?

function object2(){
   var text
   this.getData = function(){
       return{
       text:  this.text
}
}
   this.setData = function (){
       this.text = prompt ("Type anything");
}
   return this.setData();
}
   var user = new addUserObject;
       memArray.push(user.getData());
       console.log(memArray);

Solution

  • There's a lot of methods but my method is using "for" iterate to the word you want to edit and change it.

    var myArray = ["hello" , "hi"];
    console.log(myArray);
    
    function addToArray(str){
      myArray.push(str);
    }
    addToArray("yo");
    console.log(myArray);
    
    function editArray(){
      var word = prompt("Please enter which word you want to change:", "");
      if (word != null && word.length > 0){
        var found = false;
        for (var i = 0; i < myArray.length; i++){
          if (word == myArray[i]){
            found = true;
            var editWord = prompt("You want to change \"" + word + "\" to:", "");
            if (editWord != null && editWord.length > 0){
              myArray[i] = editWord;
            } else {
              console.log("You input nothing.");
            }
            break;
          }
        }
        if (!found){
          console.log("Cannot find this word");
        }
      } else {
        console.log("You input nothing.");
      }
    
    }
    editArray();
    console.log(myArray);