我使用 jquery.get()
来检索和存储对象,如下所示:
var cData =
{
"someitems":[
{
...
},
{
...
},
{
...
},
.....
]
}
我需要保留我的结构,但只获取集合中的数据。意思是,获取记录 0-3 或 4-10,诸如此类。我试过像这样使用 slice()
:
var newSet = cData.someitems.slice(0,4);
这在技术上可行,但我丢失了 json 的结构。
--- 编辑 --- 根据@meagar 请求:
我需要维护
的结构{
"someitems":[
{
...
},
{
...
},
{
...
},
.....
]
}
最佳答案
这个问题的关键在于,在 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'}
]
}
NOTE: bear in mind that after the slice operation the new
someitems
array is re-indexed, so you will find{id: 'd'}
at offset0
, and not3
关于javascript - 如何获取 json 的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27735077/