0

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})

8
  • 1
    console.log(key.some(v=>table.api_key===v))? Commented Jul 9, 2020 at 13:27
  • It returns true not that object Commented Jul 9, 2020 at 13:28
  • 2
    What do you want exactly? It is unclear what you want as an output. Commented Jul 9, 2020 at 13:28
  • console.log(!key.some(v=>table.api_key===v)&&table)? Commented Jul 9, 2020 at 13:28
  • 2
    key.includes(table.api_key) ? table : {} Commented Jul 9, 2020 at 13:36

3 Answers 3

1

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));

Sign up to request clarification or add additional context in comments.

Comments

0

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] : []

Comments

0

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.