0

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?

0

2 Answers 2

1

Object.keys()

var columns = {ContributionType: "Employer Contribution",
               Employee1: "0",
               Employee2: "0",
               Employee3: "0"
              };
var keys = Object.keys(columns);
console.log(keys);

Sign up to request clarification or add additional context in comments.

Comments

1
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);
}
}

2 Comments

Be careful when using a loop like this. You may want to check obj.hasOwnProperty(key) to check that keys aren't being added by a prototype.
Thanks for pointing that out.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.