如何将项目从JSON对象移动到另一个

时间:2011-10-23 18:38:03

标签: javascript jquery arrays json

我有两个json对象:

open_positions = [{\"id\":83,\"position\":0},{\"id\":82,\"position\":1},{\"id\":79,\"position\":2}]

done_positions = [{\"id\":85,\"position\":0},{\"id\":84,\"position\":1}]

如何从给定ID的open_positions中选择一个项目并将其移至done_positions的顶部?

由于

4 个答案:

答案 0 :(得分:2)

open_positions = [{"id":83,"position":0},{"id":82,"position":1},{"id":79,"position":2}];

done_positions = [{"id":85,"position":0},{"id":84,"position":1}];

function move_to_done(id){
  for(var pos in open_positions){
    if(open_positions[pos].id == id){
      done_positions.push(open_positions[pos]);
      delete open_positions[pos];
    }
  }
}

move_to_done(83);

答案 1 :(得分:0)

open_positions = [{"id":83,"position":0},{"id":82,"position":1},{"id":79,"position":2}];
done_positions = [{"id":85,"position":0},{"id":84,"position":1}];

id = 82;

for(key in open_positions){
    if(open_positions[key].id === id){
        myObj = open_positions[key];
    }
}

newObj = new Object();
newObj[0] = myObj;
for(key in done_positions){
    newObj[key+1] = done_positions[key];
}

console.log(newObj);

答案 2 :(得分:0)

如果您不想解析JSON,可以使用此函数切换id。

ex:http://jsfiddle.net/ZYED5/1/

function change( id ) {
    var re = new RegExp( "(,)?\\{\\\"id\\\"\\:" + id + "\\,\\\"position\\\"\\:[0-9]*\\}(,)?" );
    var match = open.match( re );
    done = done.replace( "]", "," + ( match ? match[0] : "" ) + "]" ).replace( ",,", "," ).replace( ",]", "]" );
    open = open.replace( re, "" ).replace( "}{", "},{" );
}

答案 3 :(得分:-1)

var open_positions = [{"id":83,"position":0},{"id":82,"position":1},{"id":79,"position":2}];
var done_positions = [{"id":85,"position":0},{"id":84,"position":1}];

for(var index in open_positions){ 
    if(open_positions[index]["id"]=="83"){
        done_positions.unshift(open_positions[index])
        open_positions.splice(index,1)
    }
}

也可能不需要属性“位置”,因为它是相同的索引。