I would like to know how to return true or false based on two array objects property using javascript
If arrobj1 and arrobj2 value
and country
same return true
I have tried below, may i know better way to do using javascript
Tried
for(var elem of arrobj1){
const result = arrobj2.filter(obj => obj.value === elem.value && obj.country === elem.country);
if(result.length > 0){
return true;
}
}
var arrobj1 =[
{id:1, name: "one", value:"sales", country:"MY"},
{id:2, name: "two", value:"finance", country:"PH"},
{id:3, name: "three", value:"digital", country:"SL"}
]
var arrobj2 =[
{id:4, name: "four", value:"digital", country:"SL"}
]
Expected Output
true
CodePudding user response:
Rearrange your code to start with the arrays then the sorting function
arrobj2 should be:
var arrobj2 =[
{id:4, name: "four", value:"digital", country:"SL"}
]
instead of:
var arrobj2 =[{
{id:4, name: "four", value:"digital", country:"SL"}
}]
also try console.log('true') instead if return true. You'll notice something that would help you later
CodePudding user response:
- Your code works perfectly. To use the
return
keyword, you have to wrap your code in a function and call it when needed.
Try this
var arrobj1 = [
{id:1, name: "one", value:"sales", country:"MY"},
{id:2, name: "two", value:"finance", country:"PH"},
{id:3, name: "three", value:"digital", country:"SL"}
]
var arrobj2 = [
{id:4, name: "four", value:"digital", country:"SL"}
];
function exist(arrobj1, arrobj2){
for(var elem of arrobj1){
const result = arrobj2.filter(obj => obj.value === elem.value && obj.country === elem.country);
if(result.length > 0){
return true;
}
}
return false;
}
console.log(exist(arrobj1, arrobj2));
CodePudding user response:
You can use Array#some
as follows:
const
arrobj1 =[ {id:1, name: "one", value:"sales", country:"MY"}, {id:2, name: "two", value:"finance", country:"PH"}, {id:3, name: "three", value:"digital", country:"SL"} ],
arrobj2 =[ {id:4, name: "four", value:"digital", country:"SL"} ],
found = arrobj2.some(
({value:v,country:c}) =>
arrobj1.map(
({value,country}) => `${value}|${country}`
).includes(`${v}|${c}`)
);
console.log( found );