-2

checking obj2 is already exist in obj1

expected result is true but getting false

 var obj1 =[
    {Crane:1,Ladle:1},
    {Crane:1,Ladle:2},
    {Crane:2,Ladle:1},
    {Crane:2,Ladle:2}
    ];
    var obj2={Crane:2,Ladle:2}
                        // checking obj 2 is present in obj1
    if(obj1.includes(obj2))
    {
    console.log(true);
    }
    else
    {
    console.log(false);
    }
Rainb
  • 1,965
  • 11
  • 32
shashi sampige
  • 115
  • 4
  • 15

3 Answers3

2
Please find updated code for above problem::

var obj1 = [
    { name:"string1", value:"this" },
    { name:"string2", value:"this4"},
  { name:"string5", value:"this3"},
  { name:"string12", value:"this98"}
];
 var obj2={name:"string2",value:"this4"}
var foundValue = obj1.filter(obj=>obj.name===obj2.name);

console.log(foundValue);

 if(foundValue.length>0)
    {
    console.log(true);
    }
    else
    {
    console.log(false);
    }
ChandanK
  • 31
  • 1
  • 5
1

You can do something like this,

var obj1 = [
  { Crane: 1, Ladle: 1 },
  { Crane: 1, Ladle: 2 },
  { Crane: 2, Ladle: 1 },
  { Crane: 2, Ladle: 2 }
];

var obj2 = {Crane:2,Ladle:2}

const isPresent = (arr, obj2) => arr.some(obj => obj.Crane === obj2.Crane && obj.Ladle === obj2.Ladle);

if (isPresent(obj1, obj2)) {
    console.log(true);
} else {
    console.log(false);
}
Abito Prakash
  • 4,368
  • 2
  • 13
  • 26
0

There is no simple answer to your question. For example, take a look at How to determine equality for two JavaScript objects? But in such a simple case as yours (if you have no cycle references, no special objects like Map, etc.) your can simply use stringify()

const obj1_str = JSON.stringify(obj1)
const obj2_str = JSON.stringify(obj2)
console.log(obj1_str.includes(obj2_str))
x00
  • 13,643
  • 3
  • 16
  • 40