Form array of property names found in a JavaScript Object [duplicate]

心不动则不痛 提交于 2019-12-11 20:33:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!