Greg Ostry Greg Ostry - 2 years ago 91
jQuery Question

How to check if object value in array already exsits using jquery

how to check if an object value already in an array exstis ?
If not push a value

fiddle: https://jsfiddle.net/h9zctLqz/

html:

<form>
<input type="text" id="input" name="input">
<button type="button" name="save">save</button>
</form>


jquery:

$('document').ready(function(){
$myData = [];

$('button[name=save]').on('click', function(){
var input = $('#input').val();
$myData.indexOf({'input':input}) === -1 ? $myData.push({'input':input}) : console.log('already exists');
console.log($myData);
});
});

Answer Source

The first thing you should know is that, in javascript:

({ 'input': input} === { 'input': input }) // returns false

=== compares the object reference, not the way the objects look.

That means that indexOf({input: input}) will never return anything else than -1.

You can solve this by using some. some takes a function to compare stuff, so you can write your own "equals" (instead of indexOf using ===).

if ($myData.some(item => item.input === input)) console.log("exists")
else $myData.push({input: input});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download