javascript - 如何获取 json 的一部分?

标签 javascript jquery json

我使用 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 offset 0, and not 3

关于javascript - 如何获取 json 的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27735077/

相关文章:

javascript - cvc-复合体类型.2.4。发现以元素 'dw:transform-message' 开头的无效内容

javascript - Angular JS - Ng-Repeat 问题

javascript - 为什么渲染的图标不响应状态的变化?

javascript - 使用 String 或 Date 作为对象键进行内存。

javascript - 在 Rails 3 中使用 AJAX 删除记录

php - Ajax 调用返回 301 永久移动突然

java - JsonGenerator 将 json 数据附加到文件而不覆盖

javascript - 滚动到我的页面jquery中的某个ID

php - 可排序 Portlet 更新查询

java - 从 PHP/MySQL 在 Android 上操作 JSON 对象