也许有人知道如何通过数组函数更改对象中的某些数据?
比如我有一个对象:
var nodes = [
{ topic: "Games", topicscore: 100},
{ topic: "Fun", topicscore: 550},
{ topic: "New York", topicscore: 7799},
{ topic: "Hillary", topicscore: 745},
{ topic: "Politics", topicscore: 512},
{ topic: "Trump", topicscore: 71}
];
我有一个函数:
var filterScoreValues = function(array_input){
var a_out = [];
array_input.forEach(function(x){
a_out.push(Math.ceil(x / Math.max.apply(null,array_input) * 10) + 5)
});
return a_out;
};
如何将此算法应用到对象的 topicscore
?
我写了这个,但我想要一个“漂亮”的变体,可能是通过 lodash 或类似的:
function filterScoreValues(input){
var array = input.map(function (i) {
return i.topicscore;
});
array.forEach(function(x, index){
input[index]['topicscore'] = Math.ceil(x / Math.max.apply(null, array) * 10) + 5;
});
return input;
};
我经常在我的变体上使用循环.. :(
最佳答案
how to change some data in an object via a function
使用以下优化方法(没有函数。如果需要多次调用该函数,可以将其包装到函数中):
var nodes = [
{ topic: "Games", topicscore: 100},
{ topic: "Fun", topicscore: 550},
{ topic: "New York", topicscore: 7799},
{ topic: "Hillary", topicscore: 745},
{ topic: "Politics", topicscore: 512},
{ topic: "Trump", topicscore: 71}
];
// taking max 'topicscore' at once
var max_score = Math.max.apply(null, nodes.map(function (o) {
return o.topicscore;
}));
// processing each 'topicscore' item in place(without creating temporary arrays)
nodes.forEach(function (o) {
o.topicscore = Math.ceil(o.topicscore / max_score * 10) + 5;
});
console.log(nodes);
关于JavaScript。如何通过数组函数更改对象中的某些数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41402946/