gpt4 book ai didi

Javascript 对象到数组

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:27:50 26 4
gpt4 key购买 nike

我在转换一些 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com