0

I have an object like:

obj { property1: "8898" property2: "2015-04-27 08:03:39.041" property3: "27" property4: "c10" } 

I need to convert this to an array.

My code:

var results=[]; for (var property in obj) { if (obj.hasOwnProperty(property)) { results.push(obj[property]) } } 

Here i am getting only the values. I need to have the following result ["property1":1,"property2":2] instead of [1,2]

I tried to append the property name but it did not have the desired result.

1
  • you can only do this by having an array of objects like [{'property1':1},{'property2':2}] Commented May 12, 2015 at 7:56

3 Answers 3

2
var obj = { property1: "8898", property2: "2015-04-27 08:03:39.041", property3: "27", property4: "c10", }; var results = []; for (var property in obj) { if (obj.hasOwnProperty(property)) { var str = property +':'+ obj[property]; results.push(str) } } alert(results); 

DEMO

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

1 Comment

this is what i exactly i wanted.
2

How about:

var results=[]; for (var property in obj) { if (obj.hasOwnProperty(property)) { results.push({name: property, value: obj[property]}); } } 

2 Comments

this produces a array of objects: [ { name: "prop1", value: 1 } , { name: "prop2", value: 2 }, ... ] - looks nice for me :D @user2010243, you should be more precise which result you want to receive..
i apologize if i have not communicated well. I got exactly what i wanted from the below answer by @ozil.
-1

The solution that you exactly want is here-

Considering the object-

var obj = { property1: "8898", property2: "2015-04-27 08:03:39.041", property3: "27", property4: "c10", }; 

Once you run this function-

for (var property in obj) { if (obj.hasOwnProperty(property)) { var str = obj[property]; results.push(str) } } 

The array results will have values - 8898,2015-04-27 08:03:39.041,27,c10

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.