我使用jquery.get()
检索和存储一个对象,如下所示:
var cData =
{
"someitems":[
{
...
},
{
...
},
{
...
},
.....
]
}
我需要保持我的结构,但只能获得数据集。意思是,得到0-3或4-10之类的记录。我试过像这样使用slice()
:
var newSet = cData.someitems.slice(0,4);
这在技术上可行,但我失去了json的结构。
-编辑
我需要保持…的结构
{
"someitems":[
{
...
},
{
...
},
{
...
},
.....
]
}
发布于 2015-01-01 23:20:46
这个问题的关键是,在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
数组将被重新索引,因此您将在偏移量0
而不是3
处找到{id: 'd'}
。
发布于 2015-01-01 22:28:23
您可以使用splice
方法,该方法允许您就地修改数组:
var cData =
{
"someitems":[
{
...
},
{
...
},
{
...
},
.....
]
}
cData.someitems.splice(0, 4); // This will remove the first 4 elements of the array
发布于 2015-01-01 23:08:23
如果您想要前3项,您可以使用以下内容:
newnode = {"someitems" : cData.someitems.slice(0,3)}
https://stackoverflow.com/questions/27735077
复制相似问题