如何将对象值数组的每个元素与常数相乘?
输入
[{"key":usd, "value":20 }, {"key":aed, "value":50 },{"inr":usd, "value":30 },{"key":usd, "value":40 }]
输出
[{"key":usd, "value":40 }, {"key":aed, "value":100 },{"inr":usd, "value":60 },{"key":usd, "value":80 }]
答案 0 :(得分:2)
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);
编辑:如@UncleDave所指出的那样,使用modifiedItem来实现不变性
答案 1 :(得分:1)
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);
输出
[{"key":"usd", "value":40 }, {"key":"aed", "value":100 },{"inr":"usd", "value":60 },{"key":"usd", "value":80 }];
答案 2 :(得分:1)
不更改原始数组。如果您不理解,请随时发表评论。
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);
答案 3 :(得分:0)
您可以将此示例函数用于此输入类型,否则,您必须更改此函数,将对象作为输入传递:
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
}
答案 4 :(得分:0)
您可以像这样使用Array.prototype.map()
和ES6 arrow syntax:
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);
如果需要,您可以通过返回e.value
的doubles值来返回double值:
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);