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

如何在Node.js中过滤JSON对象的键?无需第三方包实现

Filter Specific Keys from JSON Without Third-Party Libraries

Perfect question—you don’t need any external packages to pull this off; vanilla JavaScript has all the tools you need. The key is to work with your original JavaScript object (before converting it to a JSON string) to pick only the keys you want, then stringify the filtered result.

Approach 1: Explicitly Build the Filtered Object

If you only have a small number of keys to keep, the simplest way is to create a new object that includes just those properties directly:

// Assume `body` is your original JavaScript object (not yet stringified)
const filteredData = {
  FirstName: body.FirstName,
  typeform_form_submits: body.typeform_form_submits
};

// Convert the filtered object to a JSON string if needed
const json = JSON.stringify(filteredData);

This will give you exactly the output you’re looking for:

{ "FirstName":"foo", "typeform_form_submits":{ "foo":true, "bar":true, "baz":true } }

Approach 2: Dynamic Filtering with Allowed Keys

If you might add more keys to keep later, use a list of allowed keys to build the filtered object dynamically—this is more scalable:

const allowedKeys = ['FirstName', 'typeform_form_submits'];
const filteredData = Object.fromEntries(
  allowedKeys.map(key => [key, body[key]]).filter(([_, value]) => value !== undefined)
);

const json = JSON.stringify(filteredData);

Just add more keys to the allowedKeys array as needed. The filter step ensures we don’t include keys that don’t exist in the original object (optional, but adds robustness).

Quick Tip

Your original code uses JSON.stringify(body) first, which converts the object to a string. It’s way easier to manipulate the JavaScript object directly before stringifying it—parsing the string back to an object would be an unnecessary extra step.

内容的提问来源于stack exchange,提问作者trent

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:01:10