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

如何使用JavaScript将指定JSON转换为过滤空值后的目标JSON格式

JavaScript: Filter and Transform Patient JSON to Target Array Structure

Problem Overview

You need to take a patient JSON object, strip out any key-value pairs where the value is null, an empty string (""), or a whitespace-only string (" "), then convert the remaining valid pairs into an array of objects formatted with propertyName and propertyValue keys.

Original input JSON:

{ 
  "patientId": "1234", 
  "patientName": "Sai", 
  "patientFname": "Kumar", 
  "patientLname": "Gadi", 
  "city": "", 
  "zipcode": null, 
  "state":" " 
}

Solution Code

Here's a straightforward JavaScript implementation that handles both filtering and transformation in one chain:

const processPatientData = (inputObj) => {
  // Convert object to [key, value] pairs, filter, then reformat
  return Object.entries(inputObj)
    .filter(([key, value]) => {
      // Skip null values, and strings that are empty or only whitespace
      return value !== null && (typeof value !== 'string' || value.trim() !== '');
    })
    .map(([propertyName, propertyValue]) => ({ propertyName, propertyValue }));
};

// Test with your input
const rawPatientData = { 
  "patientId": "1234", 
  "patientName": "Sai", 
  "patientFname": "Kumar", 
  "patientLname": "Gadi", 
  "city": "", 
  "zipcode": null, 
  "state":" " 
};

const formattedData = processPatientData(rawPatientData);
console.log(formattedData);

Expected Output

Running this code will produce exactly the structure you need:

[ 
  { "propertyName": "patientId", "propertyValue": "1234" }, 
  { "propertyName": "patientName", "propertyValue": "Sai" }, 
  { "propertyName": "patientFname", "propertyValue": "Kumar" }, 
  { "propertyName": "patientLname", "propertyValue": "Gadi" } 
]

Breakdown of the Logic

Let's walk through what each part does:

  1. Object.entries(inputObj): Turns the input object into an array of [key, value] pairs, making it easy to loop through each property.
  2. .filter(...): We check each value to exclude:
    • Any null values (like zipcode)
    • Strings that are empty or become empty after trimming whitespace (like city and state)
  3. .map(...): Converts each filtered [key, value] pair into your desired object structure using JavaScript's object shorthand syntax for brevity.

This approach is efficient, readable, and covers all the edge cases you specified.

内容的提问来源于stack exchange,提问作者Rakesh A R

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:43:03