You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Object的api_key匹配数组元素时返回该对象?

How to Return the Object When Its 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 12:47:29