2

I have an object

myObject = {
  10: "some value",
  15: "another value",
  ...
}

can I with underscore, jquery, or plain js convert it into a list as:

myList = [
  { label: 10, value: "some value" },
  { label: 15, value: "another value" },
  ...
]
1
  • It looks more like you want to convert an object to an array with objects. Commented Jul 17, 2015 at 15:26

2 Answers 2

4

With underscore.js

myList = _.map(_.pairs(myObject), function(n){
     return {label: n[0], value: n[1]}
});

Or with plain JavaScript

myList = Object.keys(myObject).map(function(key){
    return {label: key, value: myObject[key]}
});
Sign up to request clarification or add additional context in comments.

Comments

2

You can use map to transform the object into the required form:

    var myList = _.map(myObject, function(value, key){
        return {
            label: key,
            value: value
        }
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.