我有一个包含 100.000 个对象的数组。这些对象有多个键/值对。
我的数组示例:
var data = [
{
"name": "John",
"id": 1,
"completed": "yes",
"prio": 3,
"importance": 2
},
{
"name": "Jim",
"id": 2,
"completed": "yes",
"prio": 4,
"importance": 4
}
]
如下所示,我从现有数组创建了一个新数组,但现在使用原始数组中的选定键/值对。
var newData = [];
for (var i = 0; i < data.length; i++) {
newData[i] = {"name": data[i].name, "id": data[i].id};
console.log(newData[1]);
}
如您所见,我将新数组记录到控制台。但我实际需要的是将数组 newData
存储在一个单独的文件中,我可以在其中看到数组的所有对象,就像我的示例数组 data
中一样。 能够看到 newData
的所有对象实际上并不那么重要,但对于以后处理数组会很好。例如,我想使用 R 来更好地理解数据。
我该怎么做?
注意:我在浏览器中!
我真的在为这个问题苦苦挣扎,如果有人能帮助我,我会很高兴……
谢谢!
最佳答案
你可以使用 URL.createObjectURL()连同 Blob像这样:
var TxtFile = function(text) {
let data = new Blob([text], {
type: 'text/plain'
}),
file = window.URL.createObjectURL(data);
// revoke the URL after you're done using it.
function _revokeObjectUrl() {
window.URL.revokeObjectURL(textFile);
}
return {
file: file,
destroy: _revokeObjectUrl
};
};
const data = [{
"name": "John",
"id": 1,
"completed": "yes",
"prio": 3,
"importance": 2
},
{
"name": "Jim",
"id": 2,
"completed": "yes",
"prio": 4,
"importance": 4
}
];
const newData = data.map(o => ({
name: o.name,
id: o.id
}));
document.querySelector('a').href = new TxtFile(JSON.stringify(newData)).file;
//You can still access the array.
console.log(newData);
<a download>Download file</a>
关于javascript - 如何处理大数组(100.000 个对象)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44294473/