Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for specific object key and update if exists

I have text inputs that are writing to a model. I want those objects to write to the model and update if the key exists.

For example: If I submit,

Id: "1", Value: "Foo"

And I update it with a new value:

Id: "1", Value: "Bar"

My array should read:

 0 { Id: "1", Value: "Bar"}

Not

 0 { Id: "1", Value: "Foo"}
 1 { Id: "1", Value: "Bar"}

Example here: JSFiddle

 <div id="wrapper">
      <div>
        <input id="1" type="text" value="input_1">
        <button>Button 1</button>
      </div>
      <br>
      <div>
        <input id="2" type="text" value="input_2">
        <button>Button 2</button>
      </div>
      <br>
      <div>
        <input id="3" type="text" value="input_3">
        <button>Button 3</button>
      </div>
      <br>
    </div>

jQuery -- will add to the array but not sure how to update if key exists. Looked at other examples but still not getting it

   var obj = {
        pairs: []
   }


    $("button").on("click", function() {
      var keyValuePairs = {
          id: "",
          value: ""
      }

      var input_id = $(this).prev().prop('id');
      var dynamic_value = $(this).prev().prop('value');

      if(obj.pairs.length > 0){
        $.each(obj.pairs, function(i, pair) {
          if($(this).id !== input_id){
            obj.pairs.push(keyValuePairs);
            return false;
          } else {
            obj.pairs.splice(i, 1);
            obj.pairs.push(keyValuePairs);
          }
        });
      } else {
          obj.pairs.push(keyValuePairs);
      }

      keyValuePairs.id = input_id;
      keyValuePairs.value = dynamic_value;
      console.log(obj);

   });
like image 331
Chris Davila Avatar asked Nov 26 '25 12:11

Chris Davila


2 Answers

Try this https://jsfiddle.net/y6rgm7z8/93/

$(document).ready(function() {
  var obj = {
    pairs: []
  }

  $("button").on("click", function() {
    var keyValuePairs = {
      id: "",
      value: ""
    }

    var input_id = $(this).prev().prop('id');
    var dynamic_value = $(this).prev().prop('value');

    var pair = obj.pairs.find(item => item.id === input_id)
    if(pair){
      pair.value = dynamic_value;
    } else {
      keyValuePairs.id = input_id;
      keyValuePairs.value = dynamic_value;
      obj.pairs.push(keyValuePairs);
    }

    console.log(obj);

  });


});

The find() method executes the function once for each element present in the array:

  1. If it finds an array element where the function returns a true value, find() returns the value of that array element (and does not check the remaining values)
  2. Otherwise it returns undefined

The find() is better for performance than each().

And we don't need splice() with push() for updating because after find() we have link to the object, so we can change the value.

If find() returns undefined we will push the new object to the array

like image 175
Oleg Yakovlev Avatar answered Nov 28 '25 00:11

Oleg Yakovlev


See if this helps

$(document).ready(function() {
	var obj = {
  	pairs: []
  }
  
	$("button").on("click", function() {
  	var found = false;
  	var input_id = $(this).prev().prop('id');
    var dynamic_value = $(this).prev().prop('value');

    var keyValuePairs = {
        id: input_id,
        value: dynamic_value
    }
    
      if(obj.pairs.length > 0){
        $.each(obj.pairs, function(i, pair) {
	    if(pair[Object.keys(pair)[0]] === input_id){
          	obj.pairs[i] = keyValuePairs;
            found = true;
            return false;
          }
        });
        if(!found)
      		obj.pairs.push(keyValuePairs);
      } else {
          obj.pairs.push(keyValuePairs);
      }
      
      console.log(obj);
    
  });
  

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
  <div>
    <input id="1"type="text" value="input_1">
    <button>Button 1</button>
  </div>
  <br>
  <div>
    <input id="2" type="text" value="input_2">
    <button>Button 2</button>
  </div>
  <br>
  <div>
    <input id="3" type="text" value="input_3">
    <button>Button 3</button>
  </div>
  <br>
</div>
like image 25
Scaramouche Avatar answered Nov 28 '25 02:11

Scaramouche



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!