-1

How would I write the code below in function form?

var obj = {
  name : 'Tim',
  age : 20,
  hasPets : false
};
console.log(Object.keys(obj).map(function(item){
    return obj[item];
})); //=> [ 'Tim', 20, false ]

For example--this type of function form:

 function objectToArray(obj) {
//code here
};

Thank you!

10
  • Shouldn't it be called objToArray? Commented Feb 20, 2017 at 9:43
  • Simply putting your clog code into the arrayToObject function ? What are exactly I/O you expect ? Commented Feb 20, 2017 at 9:44
  • Your question is confusing. Do you want object to array (as the title suggests), or array to object (as the example function name you provide suggests)? Commented Feb 20, 2017 at 9:44
  • 1
    Yes, I meant objectToArray. I just edited it. Sorry! I'm brand new to coding so it may be simple to you but I'm just learning. :) Thanks so much! Commented Feb 20, 2017 at 9:49
  • 1
    @sᴜʀᴇsʜᴀᴛᴛᴀ: At least close it as dupe of something like that then. The question is a dupe. The target I chose does literally the same. Don't re-open stuff like this. Even if the close reason isn't a "perfect" match, we don't need dozens of answers on simple stuff like wrapping a few lines in a function. Commented Feb 20, 2017 at 10:00

3 Answers 3

1

This should do

 function getMappedItems(obj) {
  var result =  Object.keys(obj).map(function(item){
    return obj[item];
  });
 return result;
};

Can reduce the above function a bit, but just elaborated as you learning.

https://jsfiddle.net/sureshatta/be7q88qv/

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

1 Comment

How about we at least change the function name to match what it does??
1
 var objectToArray= function (obj) {
      return Object.keys(obj).map(function(item){
          return obj[item];
      }); 
 };

Comments

0

You should use Object.prototype.objectToArray for a elegant way.

var obj = {
  name : 'Tim',
  age : 20,
  hasPets : false
};

Object.prototype.objectToArray=function(){
    return Object.keys(obj).map(function(item){
        return obj[item];
    }); 
};
console.log(obj.objectToArray())

5 Comments

Dude, don't modify Object.prototype.
@Cerbrus, Please explain why not ?
@Alexandru-IonutMihai I just knew that you will downvote me for my opinion xD FYI: I didn't downvote you.
There's plenty of articles out there, like this or this.
@Kinduser, i don't downvote you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.