繁体   English   中英

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

[英]Need to convert JSON format to another json format using JavaScript

需要使用 javascript 将以下请求格式转换为输出格式。

要求:

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

}

需要转换为以下格式但我们需要检查元素的对象键值不应为空或“”(无空格)或“”(非空)然后我们只需要按以下格式打印对象名称及其值:

输出:

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

提前致谢。

Object.entries上使用mapfilter

 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; }

这是一种简单的方法:

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);

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

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);

您可以使用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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM