如何使用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:
Object.entries(inputObj): Turns the input object into an array of[key, value]pairs, making it easy to loop through each property..filter(...): We check each value to exclude:- Any
nullvalues (likezipcode) - Strings that are empty or become empty after trimming whitespace (like
cityandstate)
- Any
.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
相关产品推荐
相关产品推荐

