1

I have a object Array

var dataArray = [
{ 'nation': 'TW', 'sales':'Jack', 'amount': 3000 },
{ 'nation': 'HK', 'sales':'Chen', 'amount': 3200 },        
{ 'nation': 'SZ', 'sales':'Tomm', 'amount': 2800 }, 
{ 'nation': 'SH', 'sales':'Alan', 'amount': 1900 },  
{ 'nation': 'JP', 'sales':'Will', 'amount': 1200 } 
] ;  

I like to do calculation of (amount *5) then push the result back to the Object array Is there a way to do that?

what i want as result

var dataArray = [
{ 'nation': 'TW', 'sales':'Jack', 'amount': 3000 ,'calv':15000},
{ 'nation': 'HK', 'sales':'Chen', 'amount': 3200 ,'calv':16000} ,        
{ 'nation': 'SZ', 'sales':'Tomm', 'amount': 2800 ,'calv':14000}, 
{ 'nation': 'SH', 'sales':'Alan', 'amount': 1900 ,'calv':9400} ,  
{ 'nation': 'JP', 'sales':'Will', 'amount': 1200 ,'calv':6000} 
] ;

4 Answers 4

1

use underscore or lodash to help

_.each(dataArray, function(v, k) {
  v['calv'] = v['amount']*5;
});

then you will get your result. or you may use it like this

for(var i in dataArray) {
  dataArray[i]['calv'] = dataArray[i]['amount'] * 5;
}
Sign up to request clarification or add additional context in comments.

Comments

1
for (var i = 0, l = dataArray.length; i < l; i++) {
    dataArray[i].calv = dataArray[i].amount * 5;
}

Comments

1

I'll try if nobody beats me to anwsering this question :p.

for(var i = 0;i < dataArray.length;++i){
  dataArray[i]['calv'] = dataArray[i]['amount'] * 5;
}

Comments

1

You could use .map method. (Note it needs a shim for old browsers)

var result = dataArray.map(function(e) { e.calv = e.amount * 5; return e;});

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.