Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore Create array of objects from object elements

Hello I have object like this:

var obj = { banana: 1425, orange: 1683}

and I need array of objects created on the basis of items. for example:

[{name: banana, value: 1425}, {name: orange, value: 1683}]

I did it in this way :

var fruits = [];
_.each(obj, function(value, name){
    fruits.push({
        name: name,
        value: value
    });
});

maybe you know an easier way?

like image 556
Agata Avatar asked Dec 25 '22 19:12

Agata


1 Answers

You can use underscore's _.map on an object :

var obj = { banana: 1425, orange: 1683};

var fruits = _.map(obj, function(value, key){
  return { name : key, value : value };
});

http://underscorejs.org/#map

like image 104
ne8il Avatar answered Dec 28 '22 08:12

ne8il