需要使用JavaScript将JSON格式转换为另一种json格式

问题描述 投票:1回答:4

需要使用javascript输出格式转换下面的请求格式。

请求:

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

}

需要转换为以下格式,但我们需要检查元素的对象keyvalue不应该为null或“”(没有空格)或“”(不为空)然后我们只需要打印对象名称及其值如下格式:

输出:

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

提前致谢。

javascript arrays json object
4个回答
3
投票

map上使用filterObject.entries

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

const newData = Object.entries(data).filter(([, v]) => ![undefined, null, ""].includes(typeof v == "string" ? v.trim() : v)).map(([key, value]) => ({
  propertyName: key, 
  propertyValue: value
}));

console.log(newData);
.as-console-wrapper { max-height: 100% !important; top: auto; }

0
投票

这是一个简单的方法:

const obj = {
  "patientId": "1234",
  "patientName": "Sai",
  "patientFname": "Kumar",
  "patientLname": "Gadi",
  "city": "",
  "zipcode":null,
  "state":" "
};
const newArr = [];

for (let key in obj) {
  if (obj[key] && obj[key].trim()) {
    newArr.push({
      propertyName: key,
      propertyValue: obj[key]
    });
  }
}

console.log(newArr);

首先,遍历对象的可枚举属性。在每次迭代中,检查值是否为空或空格。如果有正确的值,它会将新对象推送到结果数组。


0
投票

Array.reduce在这里是合适的。这样你就不必连续调用Array函数,只需多次遍历你的数组(即:Array.map() + Array.filter())。

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

let res = Object.entries(obj).reduce((acc, [key, value]) => {
  if (![undefined, null, ''].includes(typeof value === 'string' ? value.trim() : '')) {
    acc.push({
      propertyName: key,
      propertyValue: value
    });
  }
  return acc;
}, []);

console.log(res);

-2
投票

你可以使用Object.entriesreduce

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

let op = Object.entries(obj).reduce((op,[key,value])=>{
  if((value||'').trim()){
    op.push({
    'propertyName' : key,
    'propertyValue': value
   })
  }
  return op
},[])

console.log(op)
© www.soinside.com 2019 - 2024. All rights reserved.