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

时间:2019-03-30 05:55:15

标签: javascript arrays json object

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

请求:

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

}

需要转换为以下格式,但是我们需要检查元素的对象键值不应该为null或“”(无空格)或“”(不为空),那么我们只需将对象名称及其值打印为格式如下:

输出:

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

谢谢。

4 个答案:

答案 0 :(得分: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; }

答案 1 :(得分: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);

首先,您遍历对象的可枚举属性。在每次迭代中,您检查该值是否为null或空白。如果有适当的值,它将把新对象推入结果数组。

答案 2 :(得分: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);

答案 3 :(得分:-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)