假设我们有以下对象数组(真实有71000个元素,但有4个对象足以让你知道):
[
{
source: "France"
target: "Morocco"
timeN: "2008"
valueN: "252.35"
},
{
source: "France"
target: "Morocco"
timeN: "2009"
valueN: "424.12"
},
{
source: "France"
target: "Morocco"
timeN: "2010"
valueN: "152.24"
},
{
source: "France"
target: "Morocco"
timeN: "2011"
valueN: "-342.19"
}
]
如果source
为负数,如何有效地在最后一个对象上交换target
和valueN
值?我想将valueN
与-1
相乘或致电Math.abs()
,然后将source
更改为"Morocco"
,将target
更改为"France"
}。
虽然所有答案都很棒,但我已经采取了@Nina Scholz的清洁答案。然而,一旦追踪执行时间,来自@EmilS.Jørgensen的那个是性能最高的那个。我不知道为什么,但如果你不将它转换回string
valueN
,它似乎是最有效的。
答案 0 :(得分:2)
通过调用parseFloat和Math.abs来映射数组似乎是最简单的解决方案:
var data = [{
source: "France",
target: "Morocco",
timeN: "2008",
valueN: "252.35"
},
{
source: "France",
target: "Morocco",
timeN: "2009",
valueN: "424.12"
},
{
source: "France",
target: "Morocco",
timeN: "2010",
valueN: "152.24"
},
{
source: "France",
target: "Morocco",
timeN: "2011",
valueN: "-342.19"
}
];
//Fix data by remapping values
data.forEach(function (entry) {
var floatingValue = parseFloat(entry.valueN);
entry.valueN = Math.abs(floatingValue);
if (floatingValue < 0) {
//Flipping
var temp = entry.source;
entry.source = entry.target;
entry.target = temp;
}
});
console.log(data);
答案 1 :(得分:2)
var array = [{ source: "France", target: "Morocco", timeN: "2008", valueN: "252.35" }, { source: "France", target: "Morocco", timeN: "2009", valueN: "424.12" }, { source: "France", target: "Morocco", timeN: "2010", valueN: "152.24" }, { source: "France", target: "Morocco", timeN: "2011", valueN: "-342.19" }];
array.forEach(o => {
if (o.valueN < 0) {
[o.source, o.target] = [o.target, o.source];
o.valueN *= -1;
}
});
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 2 :(得分:1)
array.forEach(x=> {
if(x.valueN < 0){
[x.source, x.target] = [x.target, x.source] //swapping values between two var
x.valueN *= -1;
}
});
您可以尝试上面的代码。循环通过数组,如果找到负值,则交换变量并取消值N
答案 3 :(得分:1)
这是一个有效的解决方案:
let arr = [
{
source: "France",
target: "Morocco",
timeN: "2008",
valueN: "252.35"
},
{
source: "France",
target: "Morocco",
timeN: "2009",
valueN: "424.12"
},
{
source: "France",
target: "Morocco",
timeN: "2010",
valueN: "152.24"
},
{
source: "France",
target: "Morocco",
timeN: "2011",
valueN: "-342.19"
}
]
for (let el of arr) {
if(parseInt(el.valueN) > 0) {
continue;
}
let source = el.source;
let target = el.target;
el.target = source;
el.source = target;
el.valueN = (el.valueN * -1).toString();
}
console.log(arr);
希望你觉得这很有帮助。如果您不了解某个特定部分,您可以进一步询问我。
答案 4 :(得分:0)
只需删除减号。如果您的代码中没有其他用途。简单并完成工作。
var data = [{source: "France",target: "Morocco",timeN: "2008",valueN:"252.35"},{source: "France",target: "Morocco",timeN: "2009",valueN: "424.12"},{source: "France",target: "Morocco",timeN: "2010",valueN: "152.24"},{source: "France",target: "Morocco",timeN: "2011",valueN: "-342.19"}];
data.forEach( e => { e.valueN = e.valueN.replace('-','');});
console.log(data)
&#13;