Reputation: 41
How can I multiple each element of array of object value with a constant?
Input
[{"key":usd, "value":20 }, {"key":aed, "value":50 },{"inr":usd, "value":30 },{"key":usd, "value":40 }]
Output
[{"key":usd, "value":40 }, {"key":aed, "value":100 },{"inr":usd, "value":60 },{"key":usd, "value":80 }]
Upvotes: 1
Views: 1361
Reputation: 1007
without mutating your original array. feel free to comment if you don't understand.
let someArray = [{"key":"usd", "value":20 }, {"key":"aed", "value":50 },{"inr":"usd", "value":30 },{"key":"usd", "value":40 }]
let result = someArray.map(data=>{
return {...data, value: data.value*2}
})
console.log(result);
Upvotes: 1
Reputation: 261
const arr = [{"key":"usd", "value":20 }, {"key":"aed", "value":50 },{"inr":"usd", "value":30 },{"key":"usd", "value":40 }];
arr.map(function(value,key){
arr[key].value *=2;
});
console.log(arr);
Output
[{"key":"usd", "value":40 }, {"key":"aed", "value":100 },{"inr":"usd", "value":60 },{"key":"usd", "value":80 }];
Upvotes: 1
Reputation: 44125
You can just use Array.prototype.map()
and ES6 arrow syntax like this:
const arr = [{
"key": "usd",
"value": 20
}, {
"key": "aed",
"value": 50
}, {
"inr": "usd",
"value": 30
}, {
"key": "usd",
"value": 40
}];
const value = 2;
const result = arr.map(e => {
e.value *= value;
return e;
});
console.log(result);
And if you want to, you can just return the doubled values like this, by returning the doubles value of e.value
:
const arr = [{
"key": "usd",
"value": 20
}, {
"key": "aed",
"value": 50
}, {
"inr": "usd",
"value": 30
}, {
"key": "usd",
"value": 40
}];
const value = 2;
const result = arr.map(e => e.value *= value);
console.log(result);
Upvotes: 0
Reputation: 566
const arr = [{"key":"usd", "value":20 }, {"key":"aed", "value":50 },{"inr":"usd", "value":30 },{"key":"usd", "value":40 }];
const modifiedArr = arr.map(item => {
var modifiedItem = Object.assign({}, item);
modifiedItem.value *= 2;
return modifiedItem;
});
console.log(arr);
console.log(modifiedArr);
Edit: used modifiedItem for immutability as pointed out by @UncleDave
Upvotes: 2
Reputation: 921
you can use this sample function for this input type,in other case you have to change this function,pass your object as input:
valueChanger(input){
var tx = []
for(var x = 0;x < Object.keys(input).length ; x++){
var obj = {}
obj['key'] = input[x]['key'] // do anything with key if you want in here
obj['value'] = input[x]['value']*2
tx.push(obj)
}
return tx
}
Upvotes: 0