问题
I have the following object
var columns = {ContributionType: "Employer Contribution",
Employee1: "0",
Employee2: "0",
Employee3: "0"
};
From this I need to form an array with they property keys alone like following
var keys=["ContributionType", "Employee1", "Employee2", "Employee3"];
The number of properties is dynamic
Question: How can I achieve this using lodash or pure JavaScript?
回答1:
Object.keys()
var columns = {ContributionType: "Employer Contribution",
Employee1: "0",
Employee2: "0",
Employee3: "0"
};
var keys = Object.keys(columns);
console.log(keys);
回答2:
var arr=[];
for (var key in columns)
{
//by using hasOwnProperty(key) we make sure that keys of
//the prototype are not included if any
if(columns.hasOwnProperty(key))
{
arr.push(key);
}
}
来源:https://stackoverflow.com/questions/31542654/form-array-of-property-names-found-in-a-javascript-object