如何将对象数组中的属性值设置为反向?

时间:2018-10-01 06:24:32

标签: javascript arrays

我有一个称为阈值的对象数组:

thresholds: [{
                dType: "threshold",
                from: 0,
                to: 30,
                color: "#D91427"
            },
            {
                dType: "threshold",
                from: 30,
                to: 70,
                color: "#F2910A"
            },
            {
                dType: "threshold",
                from: 70,
                to: 120,
                color: "#219131"
            }
            ]

如何反向设置每个对象的color属性? 例如,类似这样的

thresholds: [{
                dType: "threshold",
                from: 0,
                to: 30,
                color: "#219131"
            },
            {
                dType: "threshold",
                from: 30,
                to: 70,
                color: "#F2910A"
            },
            {
                dType: "threshold",
                from: 70,
                to: 120,
                color: "#D91427"
            }
            ]

3 个答案:

答案 0 :(得分:1)

这是简单的Ariff,只需遍历thresholds数组即可。计算数组的总长度,并遍历数组的一半,交换color中对象的thresholds[]值,它们在相反的两端彼此对应,例如,第一个元素-最后一个元素,第二个元素-倒数第二个元素,依此类推...

这是代码段。希望对您有所帮助。

var thresh_len = thresholds.length-1;
for(var i = 0; i < (thresh_len/2); i++) {
    var temp = thresholds[i].color;
    thresholds[i].color = thresholds[(thresh_len - i)].color;
    thresholds[(thresh_len - i)].color = temp;
}

答案 1 :(得分:0)

  • 传递颜色数组
  • 引用对象中的该数组
  • 使用reverse()的{​​{1}}属性来反转数组,以便引用也被反转

Array

答案 2 :(得分:0)

我会从0循环到(len - 1) / 2并交换每种颜色

let thresholds = [{
                dType: "threshold",
                from: 0,
                to: 30,
                color: "#D91427"
            },
            {
                dType: "threshold",
                from: 30,
                to: 70,
                color: "#F2910A"
            },
            {
                dType: "threshold",
                from: 70,
                to: 120,
                color: "#219131"
            }
            ];

function swap(obj, i, len)
{
  let temp = obj[i].color;
  obj[i].color = obj[len - 1 - i].color;
  obj[len - 1 - i].color = temp;
}

let arrayLen = thresholds.length;

for (let i = 0; i <= Math.floor((arrayLen - 1) / 2); ++i)
{
    swap(thresholds, i, arrayLen);
}

console.log(thresholds);