Javascript 对象到数组

标签 javascript json

我在转换一些 JSON 时遇到了一些问题,我正在寻求一些帮助。这是我的问题,我有 JSON 返回以下内容:

收到的 JSON 示例(来自 CSV 文件):

[
    {
        "rating": "0",
        "title": "The Killing Kind",
        "author": "John Connolly",
        "type": "Book",
        "asin": "0340771224",
        "tags": "",
        "review": "i still haven't had time to read this one..."
    },
    {
        "rating": "0",
        "title": "The Third Secret",
        "author": "Steve Berry",
        "type": "Book",
        "asin": "0340899263",
        "tags": "",
        "review": "need to find time to read this book"
    },

    cut for brevity   

]

现在,这是一个一维对象数组,但我有一个函数需要将它传递给它,它只需要一个多维数组。我对此无能为力。我一直在网上寻找转换并发现了这段代码:

if (! obj.length) { return [];} // length must be set on the object, or it is not iterable  
   var a = [];  

   try {  
       a = Array.prototype.slice.call(obj, n);  
   }  
   // IE 6 and posssibly other browsers will throw an exception, so catch it and use brute force  
   catch(e) {  
       Core.batch(obj, function(o, i) {  
           if (n <= i) {  
               a[i - n] = o;  
           }  
       });  
   }  

   return a;  

但我的代码一直卡在“无对象长度”部分。当我遍历每个对象时,我一个字符一个字符地得到。不幸的是,这些字段名称(评级、标题、作者)等并不是一成不变的,我无法使用 obj.Field 表示法访问任何内容。

我坚持这个;有没有办法将这些对象转换为数组,还是我必须回到开头并转储 JSON?

最佳答案

有一个很好的 JavaScript 库叫做 Undersore.js它执行所有类型的对象/数组操作。

使用它,您可以像这样轻松地进行转换

_(json).each(function(elem, key){
    json[key] = _(elem).values();
});

关于Javascript 对象到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6215171/

相关文章:

json - 在 Go 中将组合对象转换为 json

java - jackson ,读/写嵌套属性

javascript - 如何在AngularJS中更改资源的标题

javascript - 输出需要 3 个独特的段落。

javascript - 如何在 JavaScript 中删除 GridView 中的所有行?

javascript - 未知错误 : Runtime. 评估抛出异常:SyntaxError:意外的 token var

javascript - AngularJS 从外部 URL 获取 JSON 数据

javascript - 将类添加到上一个元素

c++ - 如何使用 libjson 创建数组?

mysql - 解析 R 数据帧的 JSON 列