如何在Object的api_key匹配数组元素时返回该对象?
api_key Matches an Element in the Array Your current code uses filter() on the key array, but filter() works by returning a boolean to decide whether to keep the current element of the array. When you return [table], that’s a truthy value—so filter() ends up returning the matching key string ('1234') instead of the table object you want.
Here are a few clean, efficient ways to fix this and get your desired output:
Solution 1: Check Existence First (Simplest Approach)
First verify if the key array contains the table.api_key, then return the object directly if it does:
var table = { api_key: "1234", data: [{ temperature: 100, humidity: 200 }] }; var key = ['1234', '345']; const value = key.includes(table.api_key) ? table : null; console.log(value); // Output: { api_key: "1234", data: [{ temperature: 100, humidity: 200 }] }
Solution 2: Use find() for Explicit Matching
If you need to handle more complex matching logic later, use find() to locate the matching key, then return the table object if a match exists:
var table = { api_key: "1234", data: [{ temperature: 100, humidity: 200 }] }; var key = ['1234', '345']; const matchingKey = key.find(val => val === table.api_key); const value = matchingKey ? table : null; console.log(value); // Output: { api_key: "1234", data: [{ temperature: 100, humidity: 200 }] }
Why Your Original Code Didn’t Work
Let’s break down the issue with your initial code:
const value = key.filter(val => { if(table.api_key === val){ console.log({table}) return [table]; // This is truthy, so filter keeps the current `val` ('1234') } }); console.log({value}); // Output: { value: ['1234'] }
filter() builds a new array with elements that pass the test (your return value is truthy here). Instead of getting the table object, you end up with the matching key string wrapped in an array.
Content of the question comes from Stack Exchange, question author Raghul SK

