2015-01-01 80 views
1

我用jquery.get()检索和存储一个对象,有点像这样:如何获取json的某些部分?

var cData = 
{ 
    "someitems":[ 
      { 
       ... 
      }, 
      { 
       ... 
      }, 
      { 
       ... 
      }, 
      ..... 
    ] 
} 

我需要让我的结构,但只能在套中获取数据。意思是,获得0-3或4-10的记录,就像那样。我试着用slice()这样的:

var newSet = cData.someitems.slice(0,4); 

,在技术上的作品,但我失去了JSON的结构。

---编辑--- 每@meagar要求:

我需要保持

{ 
    "someitems":[ 
      { 
       ... 
      }, 
      { 
       ... 
      }, 
      { 
       ... 
      }, 
      ..... 
    ] 
} 
+2

你将必须更清楚你的意思,“失去结构”。一旦你解析了它,它就不是JSON,它只是一个JavaScript数组,当你“分片”时它不会“丢失”任何结构。返回的项目将与原始数组中的项目相同。 – meagar

+0

'cData.someitems = cData.someitems.slice(0,4);'您可能想要创建该对象的副本。 – freakish

+0

@meagar - 基本上我需要维护'{“someitems”:[...]}结构。 – dcp3450

回答

1

这个问题的关键在于,没有一种标准的深度克隆javascript对象的方法,如果您希望在多个范围内重复您的操作,您仍然可以更好地执行此操作保持这些修改的JSON结构。

以下显然是考虑到实际JSON数据可能比示例中使用的更复杂的事实。

var cData = { 
 
    "someitems": [ 
 
      {"id": 'a'}, 
 
      {"id": 'b'}, 
 
      {"id": 'c'}, 
 
      {"id": 'd'}, 
 
      {"id": 'e'} 
 
    ] 
 
}; 
 

 
/// there are better ways to clone objects, but as this is 
 
/// definitely JSON, this is simple. You could of course update 
 
/// this function to clone in a more optimal way, especially as 
 
/// you will better understand the object you are trying to clone. 
 
var clone = function(data){ 
 
    return JSON.parse(JSON.stringify(data)); 
 
}; 
 

 
/// you could modify this method however you like, the key 
 
/// part is that you make a copy and then modify with ranges 
 
/// from the original 
 
var process = function(data, itemRange){ 
 
    var copy = clone(data); 
 
    if (itemRange) { 
 
     copy["someitems"] = data["someitems"].slice(
 
      itemRange[0], 
 
      itemRange[1] 
 
     ); 
 
    } 
 
    return copy; 
 
}; 
 

 
/// output your modified data 
 
console.log(process(cData, [0,3]));

上面的代码应该输出具有以下结构的对象:

{ 
    "someitems": [ 
      {"id": 'a'}, 
      {"id": 'b'}, 
      {"id": 'c'} 
    ] 
} 

...如果你改变process(cData, [0,3])process(cData, [3,5])您将获得:

{ 
    "someitems": [ 
      {"id": 'd'}, 
      {"id": 'e'} 
    ] 
} 

注:记住,切片手术后新someitems数组重新索引,所以你会发现在{id: 'd'}偏移0,而不是3

1

结构你可以使用splice方法,它允许你修改阵列IN-地点:

var cData = 
{ 
    "someitems":[ 
      { 
       ... 
      }, 
      { 
       ... 
      }, 
      { 
       ... 
      }, 
      ..... 
    ] 
} 

cData.someitems.splice(0, 4); // This will remove the first 4 elements of the array 
+0

对。这给我一个数组。我需要像这样保持json格式:'{“someitems”:[[...]}' – dcp3450

+0

当然,'cData'实例在调用'splice'方法后保持其结构,如我的答案所示。只有'someitems'数组从前4个元素中剥离出来,看起来像是您想要实现的。 –

+0

可以说我有'{“someitmes”:[{“id”:1},{“id”:2},{“id”:3},{“id”:4}]}'我想要前三个产生'{“someitmes”:[{“id”:1},{“id”:2},{“id”:3}]}' – dcp3450

0

如果你想第3项,你可以这样做:

newnode = {"someitems" : cData.someitems.slice(0,3)}