0

Just exists a underscoreJs method to convert a Object having some properties to an Collection of objects having a key property?

I mean if exists a simple method in underscorejs that is equivalent of this:

function objectToCollection(obj, propertyKey) {
    return _.map(obj, function(o, key) {
        b[propertyKey] = key;
        return o;
    });
}

var obj = {
    prop1: {val:2},
    prop2: {val:3},
    prop3: {val:5},
    prop4: {val:7}
};

objectToCollection(obj, 'name');

Result:

[
    {name: 'prop1', val: 2},
    {name: 'prop2', val: 3},
    {name: 'prop3', val: 5},
    {name: 'prop4', val: 7}
]
stefcud
  • 2,220
  • 4
  • 27
  • 37

2 Answers2

2

You can use Object.keys and map

var output = Object.keys(obj).map( s => ({...obj[s], name:s}) )

Demo

var obj = {
    prop1: {val:2},
    prop2: {val:3},
    prop3: {val:5},
    prop4: {val:7}
};
var output = Object.keys(obj).map( s => ({...obj[s], name:s}) );

console.log( output );
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • I ask if exists a simple method, not a short implementation – stefcud Apr 02 '18 at 12:34
  • 1
    Sure, can you define and elaborate on *simple method* in your question itself? – gurvinder372 Apr 02 '18 at 12:34
  • if just exist a method inside undescorejs similar to *objectToCollection* function. the question (look the title) is relative to *underscorejs* not javascript in general – stefcud Apr 02 '18 at 12:43
0

Since underscore's map (even all the methods that works on collection) can work directly on Object, for this kind of transformation no extra function is needed there.

_.map(obj) it will just transform all the values of the object to a collection

Here is an example for your specific case (transformation), where you want to preserve the keys inside each object with a property name:

var obj = {
    prop1: {val:2},
    prop2: {val:3},
    prop3: {val:5},
    prop4: {val:7}
}
var array = _.map(obj, (v, name) => ({...v, name}));

console.log(array)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
Koushik Chatterjee
  • 4,106
  • 3
  • 18
  • 32