1

I have an array of objects containing a property called 'memory' whose value is in MB. I need to convert the array containing the object with 'memory' value in GB. How can I do it using Underscore.js.

Below is the code:

 var parseSize = function(obj){
   if (obj === 0 ){
    return 0;
   } else {
     return  parseFloat(obj/1024).toFixed(2);
   }
 }

   var testData=[
       { name: 'ddd',Vcpu: 2, memory: 4096, os: 'Microsoft Windows Server 2008 (32-bit)'}, 
       { name: 'eee',Vcpu: 2, memory: 2040, os: 'Microsoft Windows Server 2008 (32-bit)'},
       { name: 'ddd',Vcpu: 2, memory: 4096, os: 'Microsoft Windows Server 2008 (32-bit)'}, 
       { name: 'eee',Vcpu: 2, memory: 2040, os: 'Microsoft Windows Server 2008 (32-bit)'}
   ];

  testData =_.invoke(testData , function(){
              testData['memory'] = parseSize(testData['memory']) + " GB";
            });
  console.log(testData);

The above code is not working. PLease let me know where I am going wrong.

Adding the Jsfiddle link: http://jsfiddle.net/prashdeep/k29zuba2/

4 Answers 4

2

The answer of what went wrong in your code:

  1. You should use _.each
  2. You should not reassign testData with the result
  3. You should be accessing "memory" property on each item in testData, not on testData itself

So change your latter part of code to:

_.each(testData , function(datum){
    datum['memory'] = parseSize(datum['memory']) + " GB";
});

console.log(testData);
Sign up to request clarification or add additional context in comments.

Comments

1

You can use map. This is built into JavaScript since ES5:

var result = testData.map(function(x) {
    x.memory = parseSize(x.memory) + ' GB'
    return x
})

Comments

1

Using underscore _.each you can do the following:

 _.each(testData , function( item ){
    item['memory'] = parseSize(item['memory']) + " GB";
 });

See jsfiddle example.

Don't use map or forEach if you want support for older browsers like IE8.

Comments

0
var parseSize = function(obj){
   if (obj === 0 ){
    return 0;
   } else {
     return  parseFloat(obj/1024).toFixed(2);
   }
 }

   var testData=[
       { name: 'ddd',Vcpu: 2, memory: 4096, os: 'Microsoft Windows Server 2008 (32-bit)'}, 
       { name: 'eee',Vcpu: 2, memory: 2040, os: 'Microsoft Windows Server 2008 (32-bit)'},
       { name: 'ddd',Vcpu: 2, memory: 4096, os: 'Microsoft Windows Server 2008 (32-bit)'}, 
       { name: 'eee',Vcpu: 2, memory: 2040, os: 'Microsoft Windows Server 2008 (32-bit)'}
   ];

  testData.forEach(function(d){ d.memory = parseSize(d.memory); });

  console.log(testData);

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.