2011-07-17 51 views
2
  • 如何删除键值为空值并形成新的json。
  • 如何迭代这个响应....在哪里我想显示..这个键 ==>相应的值。

回答

2

对于初学者来说,修复你的javascript对象因为你发布的内容充满了错误。一旦你有一个有效的数组:

var values = [{ 
    'SPO2': 222.00000, 
    'VitalGroupID': 1152, 
    'Temperature': 36.6666666666667, 
    'DateTimeTaken': '/Date(1301494335000-0400)/', 
    'UserID': 1, 
    'Height': 182.88, 
    'UserName': null, 
    'BloodPressureDiastolic': 80, 
    'Weight': 100909.090909091, 
    'TemperatureMethod': 'Oral', 
    'Resprate': null, 
    'HeartRate': 111, 
    'BloodPressurePosition': 'Standing', 
    'VitalSite': 'Popliteal', 
    'VitalID': 1135, 
    'Laterality': 'Right', 
    'HeartRateRegularity': 'Regular', 
    'HeadCircumference': '', 
    'BloodPressureSystolic': 120, 
    'CuffSize': 'XL' 
}, { 
    'SPO2': 100.00000, 
    'VitalGroupID': 1113, 
    'Temperature': 32.7777777777778, 
    'DateTimeTaken': '/Date(1299856980000-0500)/', 
    'UserID': 1, 
    'Height': 0, 
    'UserName': 'Admin', 
    'BloodPressureDiastolic': 78, 
    'Weight': 49895.1607, 
    'TemperatureMethod': '', 
    'Resprate': null, 
    'HeartRate': null, 
    'BloodPressurePosition': 'Sitting', 
    'VitalSite': '', 
    'VitalID': 1096, 
    'Laterality': '', 
    'HeartRateRegularity': 'Regular', 
    'HeadCircumference': '', 
    'BloodPressureSystolic': 120, 
    'CuffSize': '' 
}]; 

那么你可以遍历它:

for (var i = 0; i < values.length; i++) { 
    // this will run for each element of the initial array 

    for (var propertyName in values[i]) { 
     // this will run for each property of the element 
     var propertyValue = values[i][propertyName]; 

     if (propertyValue == null) { 
      // if the value is null remove it 
      delete values[i][propertyName]; 
     } else { 
      console.log('name: ' + propertyName + ', value: ' + propertyValue); 
     } 
    } 
} 

Demo

+0

我如何知道对象的键的总数... –

+0

@John Cooper,请看这里:http://stackoverflow.com/questions/126100/how-to -efficiently计数最数的密钥的属性-的-AN-对象中的JavaScript –

5

1:这将删除任何错误的值,即空值,未定义或空字符串。尽管你可以专门检查空值。确保你阅读并理解删除操作,这会让很多人陷入困境。

for(var key in someObject) { 
    if(!someObject[key]) { 
     delete someObject[key]; 
    } 
} 

2:可以遍历对象的所有属性和值,像这样:

for(var key in someObject) { 
    console.log("The value of " + key + " is " + someObject[key]); 
} 
+2

这不会删除假钥吗? –

1

删除属性:

if (objectName.propertyName === null) { 
    delete objectName.propertyName; 
} 

迭代扔性质:

for (var key in objectName) { 
    document.write(objectName[key]); 
} 
+0

'undefined'和'null'具有相似的语义。 使用'=='更稳定 –

1
var array_of_json_hashes; 

var result = []; 

for(var i = 0; i < array_of_json_hashes.length; i++) { 
    result[i] = {}; 
    var h = array_of_json_hashes[i]; 
    for (var key in h) { 
    console.log(key); 
    console.log(h[key]); 
    if (h.hasOwnProperty(key)) { 
     if(h[key]) { 
     result[i][key] = h[key]; 
     } 
    } 
    } 
} 

console.log(result);