How to check for specific object key and update if exists

Chris Davila

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);

   });
Oleg Yakovlev

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to check if key exists in array of object

Check if a specific key exists in firebase

javascript - how to check if exists child object value of key in object?

Check if key exists in nested object

Elasticsearch check a key exists in an object

Check if formdata object key exists

How to check if an object exists

How to check if a key exists in Json Object and get its value

How to check if a specific object already exists in an array before adding it

How to check if an object with specific id exists on a canvas with fabricjs

C++: How to check that an object with a specific property exists in a set

Firestore check if a key exists, then check if a specific field in the same collection exists

In Twig, check if a specific key of an array exists

Check if Specific Key Exists in Json Array

Check if key of dictionary exists in a specific column in Kusto?

How to check if foreign key exists?

How to check if a array key exists?

How to check the key is exists in collection or not

How to check if a json key exists?

How To Check If A Key in **kwargs Exists?

How To Check If A Key in **kwargs Exists?

How to check if an appSettings key exists?

How to check if a key exists in Partial?

How to update if key exists - sequelize

Check if object key exists in array of object and add if not exists

check if key and its value in exists in object

libGDX TiledMap: Check if object exists at a specific cell

Check if object with specific value exists in List

How to Filter an Array of Object and check if Specific key has a value in an Array

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive