0

I want to check if the input value is present in obj, I display an alert ('num found'), then I push that num in the second obj2, and this num becomes disabled from the obj1, (I mean when I check again that num, it should be not available), I don't know if the best way is to add some extra key used in object, or to create a new object obj2 then check first on it if the values have already been used.

var obj = [
    {"id":1, "num":123, "val":20, "type":"weekend"},
    {"id":2, "num":456, "val":30, "type":"weekend"},
    {"id":3, "num":789, "val":15, "type":"semaine"},
    {"id":4, "num":101, "val":25, "type":"semaine"}
];

var obj2 = [
];

html:

<input id="code"/> // val = 15

Js

jQuery("input").on("keydown",function search(e) {
        if(e.keyCode == 13) { //when hit enter
            var tik = jQuery(this).val();
            console.log(tik);

            var obj = [
                {"id":1, "num":123, "val":20, "type":"week"},
                {"id":2, "num":456, "val":30, "type":"week"},
                {"id":3, "num":789, "val":15, "type":"day"},
                {"id":4, "num":101, "val":25, "type":"day"}
            ];

            if (tik in obj2.num) { // It doesn't work for me
                alert("num found");
            //I push this value to obj2
            ...
            } else {
                alert("num not found");
                //I don't push to obj2
            }
PЯINCƎ
  • 646
  • 10
  • 28
  • It's not perfectly clear exactly what you're trying to do, however I am certain that [this question](https://stackoverflow.com/questions/7364150/find-object-by-id-in-an-array-of-javascript-objects) is the logic you need to use to find the objects in the array by the property value. – Rory McCrossan Dec 10 '18 at 12:33
  • your `obj2` is defined as an array, which wouldn't have the property `num`, maybe you could use `obj2.indexOf( tik )` or `obj2.includes( tik )` instead? (I do not know why you want to move it into `obj2` still though, if you have just found it there? Neither do I understand why you define `obj` in your event handler but `obj2` outside of the array – Icepickle Dec 10 '18 at 12:34
  • My need is: i have a list of a unique codes, when user enter some code in input, i check the value if is in the object, if yes I alert ok, and if user enter again the same value as the first, i display ko. – PЯINCƎ Dec 10 '18 at 12:55

1 Answers1

0

Your condition can be like this :

 if (obj.find(o => o.num === parseInt(tik))) {
   alert("num found");
   //I push this value to obj2
 } else {
   alert("num not found");
   //I don't push to obj2
 }
lbhise
  • 136
  • 5