如何从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",&# 34; BusinessCategory"," PriorityGroup"
我将数据传递给一个对象,但我不确定循环的最佳方法并创建一个独特的属性列表。
答案 0 :(得分:0)
Object.keys()
方法返回给定对象自己的可枚举属性的数组,其顺序与for ... in
循环提供的顺序相同(不同之处在于for-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>');
&#13;
答案 1 :(得分: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