Goderaftw
Goderaftw

Reputation: 159

Change key's value in array of objects with javascript?

I am building a page that allows customers to change information, which is then passed to the admin team to verify before accepting. I am trying to keep the form dynamic in only passing information that was changed by the customer. I'm using the function below to create an array of objects:

$('input, textarea, select').change(function(){
    var key = $(this).attr('name');
    var obj = {};
    obj[key] = $(this).val();
    myArray.push(obj);
});

Which is working correctly, however today I noticed that when changing the field multiple times it created multiple objects with the same name.

My question is how can I find the key which is dynamic and change the value if it exists in the array?

I tried using:

$.each(myArray, function( key, value ) {
    console.log(key, value);
});

But this outputs the index and then the complete object, I need to find the key of the object and then change the value if it already exists.

Upvotes: 1

Views: 3976

Answers (1)

Z.Z.
Z.Z.

Reputation: 704

The variable myArray is a array not a object, so the key is just the index of the object in the array.

To check if the object with the specific key exists,

function getObjWithKey(myArray, key){
   var retVal;
   $.each(myArray, function(index, obj) {
       if(key != undefined && obj[key]){
           retVal = obj;
           return false;
       }
   });
   return retVal;        
}

Upvotes: 1

Related Questions