2011-07-17 49 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);