简体   繁体   English

如何移动/更改 JavaScript 对象数组 (JSON) 的位置/顺序?

[英]How to move/change the position/order of an JavaScript Object array(JSON)?

Let's say I have this javascript object array,假设我有这个 javascript 对象数组,

[{a:'a', b:2, c:true}, {a:'b', b:3, c:true}, {a:'a1', b:3, false}]

Let's say I need to move the object at index 0 to 2. I have tried this function with no luck.假设我需要将索引 0 处的对象移动到 2。我尝试过这个函数但没有成功。

   Array.prototype.move = function (old_index, new_index) {
    if (new_index >= this.length) {
        var k = new_index - this.length;
        while ((k--) + 1) {
            this.push(undefined);
        }
    }
    this.splice(new_index, 0, this.splice(old_index, 1)[0]);
  };

The object array is not correct, it needs the 'c' variable in the last item:对象数组不正确,它需要最后一项中的 'c' 变量:

[{a:'a', b:2, c:true}, {a:'b', b:3, c:true}, {a:'a1', b:3, c:false}];

Working example: http://jsfiddle.net/WgLKc/1/工作示例: http : //jsfiddle.net/WgLKc/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM