2015-01-01 79 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)}