javascript - TypeError: xxx.flatMap 不是函数
问题描述
我正在尝试将 xml 文件解析为 json,然后将其批量索引到弹性搜索中。这是我的代码:
require('array.prototype.flatmap').shim()
const fs = require('fs');
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
node: 'http://localhost:9200'
})
const xml2js = require('xml2js');
const parser = new xml2js.Parser();
fs.readFile(__dirname + '/data.xml', (err, data) => {
parser.parseString(data, (err, result) => {
const jsonString = JSON.stringify(result);
var jsonObj = JSON.parse(jsonString);
run(jsonObj).catch(console.log)
});
});
async function run (dataset) {
await client.indices.create({
index: 'entity'
}, { ignore: [400] })
console.log(dataset)
const body = dataset.flatMap(doc => [{ index: { _index: 'entity' } }, doc])
// code removed for brevity
}
我可以 console.log(dataset) 并查看它的数据。
但是当我运行时flatMap
,它会遇到错误:
TypeError: dataset.flatMap is not a function
但是,如果我像下面这样传递硬编码值dataset
,它就可以工作。
const dataset = [{
id: 1,
text: 'If I fall, don\'t bring me back.',
user: 'jon1',
date: new Date()
}, {
id: 2,
text: 'Winter is coming',
user: 'ned',
text: 'A Lannister always pays his debts.',
user: 'tyrion',
date: new Date()
}, {
id: 4,
text: 'I am the blood of the dragon.',
user: 'daenerys',
date: new Date()
}, {
id: 5, // change this value to a string to see the bulk response with errors
text: 'A girl is Arya Stark of Winterfell. And I\'m going home.',
user: 'arya',
date: new Date()
}]
这是我的 package.json
{
"name": "elasticsearch",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"@elastic/elasticsearch": "^7.11.0",
"array.prototype.flatmap": "^1.2.4",
"express": "^4.17.1",
"fs": "0.0.1-security",
"util": "^0.12.3",
"xml2js": "^0.4.23"
},
"devDependencies": {
"eslint": "^7.19.0"
}
}
解决方案
该变量dataset
包含一个对象。你必须打电话flatMap
。dataset.PFA.Entity
const body = dataset.PFA.Entity.flatMap(doc => [
{ index: { _index: 'entity' } },
doc,
])
推荐阅读
- python-3.x - 这个 lambda 函数如何将逗号放在千位
- c++ - dlopen c++ 库和带有 c++ 样式参数的 dlsym 调用函数
- mongodb - 如何查询对象数组的某些元素?(mongodb)
- javascript - JS中的“消毒剂”是什么意思?
- sql-server - 如何使用 Entity Framework 处理多种数据库类型支持
- python-3.x - 如何在第一次出现字符串后插入 string1,在第二次出现字符串后插入 string2,依此类推?
- javascript - 将选中的 Li 移动到 UL 的底部
- html - CSS Flexbox:将两个项目保留在同一列中
- java - java中的模运算符
- sapui5 - UI5:隐藏 UploadSet 的“未找到文件”图标