gpt4 book ai didi

JavaScript。如何通过数组函数更改对象中的某些数据?

转载 作者:行者123 更新时间:2023-11-30 11:44:43 26 4
gpt4 key购买 nike

也许有人知道如何通过数组函数更改对象中的某些数据?

比如我有一个对象:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com