2016-03-04 162 views
0

如何從javascript對象創建不同屬性的列表?Javascript對象屬性清單

下面是一個簡單的字符串,是動態創建這個字符串(我不知道是什麼屬性和值可能含有。

[{ 
    "ID": 331, 
    "DynamicString": "", 
    "MyDate": "", 
    "TestCheckbox": "false", 
    "TestTA": "", 
    "BusinessCategory": "Regulatory", 
    "PriorityGroup": "Must Do" 
}, { 
    "ID": 335, 
    "DynamicString": "hjkhjkhjk", 
    "MyDate": "17/02/2016", 
    "TestCheckbox": "true", 
    "TestTA": "hjkhjkhjk", 
    "BusinessCategory": "Regulatory", 
    "PriorityGroup": "Should Do" 
}, { 
    "ID": 336, 
    "DynamicString": "What about this", 
    "MyDate": "26/05/2016", 
    "TestCheckbox": "false", 
    "TestTA": "What about this", 
    "BusinessCategory": "Machinery of Government", 
    "PriorityGroup": "Should Do" 
}] 

我想輸出是

「 ID,DynamicString,MyDate,TestCheckBox,TestTA,BusinessCategory,PriorityGroup

我將數據傳遞給一個對象,但我不確定循環並創建一個不同的屬性列表的最佳方式。

+0

已每個項目相同的屬性? –

回答

0

試試這個

var arr = [{"ID":331,"DynamicString":"","MyDate":"","TestCheckbox":"false","TestTA":"","BusinessCategory":"Regulatory","PriorityGroup":"Must Do"},{"ID":335,"DynamicString":"hjkhjkhjk","MyDate":"17/02/2016","TestCheckbox":"true","TestTA":"hjkhjkhjk","BusinessCategory":"Regulatory","PriorityGroup":"Should Do"},{"ID":336,"DynamicString":"What about this","MyDate":"26/05/2016","TestCheckbox":"false","TestTA":"What about this","BusinessCategory":"Machinery of Government","PriorityGroup":"Should Do"}]; 
function arrayUnique(array) 
{ 
    var a = array.concat(); 
    for(var i=0; i<a.length; ++i) 
    { 
     for(var j=i+1; j<a.length; ++j) 
     { 
      if(a[i] === a[j]) 
       a.splice(j--, 1); 
     } 
    } 
    return a; 
} 
var output = []; 
arr.forEach(function(value){ output = output.concat(Object.keys(value)) });//concatenate all the items 
console.log (arrayUnique(output)); //print the unique elements 
0

使用Object.keys()

Object.keys()方法返回給定的對象自身的枚舉的屬性的陣列,以相同的順序作爲由for ... in環路(不同之處在於一個用於-in循環枚舉屬性提供在原型鏈中)。

如果數組項具有相同的屬性,那麼這將工作:

var properties = Object.keys(Array[0]); 

如果不是這將迭代對所有對象及其鍵幫助。

var array = [{ "ID": 331, "DynamicString": "", "MyDate": "", "TestCheckbox": "false", "TestTA": "", "BusinessCategory": "Regulatory", "PriorityGroup": "Must Do" }, { "ID": 335, "DynamicString": "hjkhjkhjk", "MyDate": "17/02/2016", "TestCheckbox": "true", "TestTA": "hjkhjkhjk", "BusinessCategory": "Regulatory", "PriorityGroup": "Should Do" }, { "ID": 336, "DynamicString": "What about this", "MyDate": "26/05/2016", "TestCheckbox": "false", "TestTA": "What about this", "BusinessCategory": "Machinery of Government", "PriorityGroup": "Should Do" }], 
 
    properties = function (array) { 
 
     var o = {}; 
 
     array.forEach(function (a) { 
 
      Object.keys(a).forEach(function (k) { 
 
       o[k] = true; 
 
      }); 
 
     }); 
 
     return Object.keys(o); 
 
    }(array); 
 

 
document.write('<pre>' + JSON.stringify(Object.keys(array[0]), 0, 4) + '</pre>'); 
 
document.write('<pre>' + JSON.stringify(properties, 0, 4) + '</pre>');