Reputation: 1390
I want to compare the object with the given array, the object that I am using is mentioned below
var table = { api_key: "1234", data: [{ temperature: 100, humidity: 200 }] };
The array that I used is mention below :
var key = [ '1234', '3456' ]
the code that is used to return the object when the values of array and object api_key is equal mention below
const value = key.filter(val => {
if(table.api_key === val){
console.log({table})
return [table];
}
});
but when I use that code am not getting the return value of that given object. How to return the object when the array value and object api_key values are same
I want to return the same object when condition satisfies example output:
{ api_key: "1234", data: [{ temperature: 100, humidity: 200 }] };
var table = { api_key: "1234", data: [{ temperature: 100, humidity: 200 }] };
var key = [ '1234', '345' ]
const value = key.filter(val => {
if(table.api_key === val){
console.log({table})
return [table];
}
});
console.log({value})
Upvotes: 0
Views: 69
Reputation: 854
I think this one is your desired answer
var table = { api_key: "1234", data: [{ temperature: 100, humidity: 200 }] };
var key = [ '1234', '3456' ]
function matchKeys(table){
if(key.includes(table.api_key)){
return table;
}else {
return "not found";
}
}
console.log(matchKeys(table))
Upvotes: 0
Reputation: 23
Given that you only have one possible "result" in that 'table', due to its nature of being a single object with only one field to determine the case...
You actually have a pretty simple case that doesn't require any complex composition
const tableKeyFound = keys.some(k => table.api_key === k)
const table = tableKeyFound ? [table] : []
Upvotes: 0
Reputation: 5308
You can create a method and pass the object and array to it and return accordingly. Something like this you can implement:
const table = { api_key: "1234", data: [{ temperature: 100, humidity: 200 }] };
const key = [ '1234', '3456' ];
const getObjectIfMatch = (obj, keyArr)=>keyArr.includes(obj.api_key) ? obj : {}
console.log(getObjectIfMatch(table, key));
Upvotes: 1