1

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.

2
  • Before pushing you have to check if the object exists in myArray. You could use Lodash's method findIndex Commented May 9, 2016 at 18:33
  • I posted an answer but I think I'm actually not understanding your question. Could you post an example of what you want your array of objects to look like? Commented May 9, 2016 at 18:55

1 Answer 1

1

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;        
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Z.Z, this actually answered my question but I realized the way I was doing this was pointless. I was creating an array then filling it with objects, then converting it to an object before passing it to PHP anyway. I have since just used an object to begin with and solved my issues. I appreciate everyone's help.

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.