arrays - 弹性搜索使用 javascript 将 json 对象数组展平为单级
问题描述
我面临将我的弹性查询响应(只有我想要 _source 详细信息)扁平化为单级数组的问题。
请在下面找到弹性响应:
使用( response.hits.hits )我能够访问数据数组,但无法将对象数组展平为单层
当前数组:
var current_array = [
{
"_id": "gSdhs8aPjcUjiIs6ey85",
"_score": 1,
"_source": {
"business_type": "Primary Only",
"ceo_name": "Tim Cook",
"city": "San Ramon",
"company_id": "gSdhs8aPjcUjiIs6ey85",
"company_name": "Apple Inc."
}
},
{
"_id": "v2bdB5F3PbLzziayKikS",
"_score": 1,
"_source": {
"bankruptcy_activity": "No",
"business_type": "Primary Only",
"ceo_name": "Andrew N. Liveris",
"city": "New York",
"company_id": "v2bdB5F3PbLzziayKikS",
"company_name": "General Electric",
"country": "United States"
}
}
];
期望的结果:
var desired_array = [{
"_id": "gSdhs8aPjcUjiIs6ey85",
"_score": 1,
"_source_business_type": "Primary Only",
"_source_ceo_name": "Tim Cook",
"_source_city": "San Ramon",
"_source_company_id": "gSdhs8aPjcUjiIs6ey85",
"_source_company_name": "Apple Inc."
},
{
"_id": "v2bdB5F3PbLzziayKikS",
"_score": 1,
"_source_business_type": "Primary Only",
"_source_ceo_name": "Andrew N. Liveris",
"_source_city": "New York",
"_source_company_id": "v2bdB5F3PbLzziayKikS",
"_source_company_name": "General Electric",
"_source_country": "United States"
}
];
我尝试了下面的代码,但它正在转换为我不想要的单个数组:
var flattenObject = function (ob) {
var toReturn = [];
var flatObject;
for (var i in ob) {
if (!ob.hasOwnProperty(i)) {
continue;
}
if ((typeof ob[i]) === 'object') {
flatObject = flattenObject(ob[i]);
for (var x in flatObject) {
if (!flatObject.hasOwnProperty(x)) {
continue;
}
toReturn[i + (!!isNaN(x) ? '.' + x : '')] = flatObject[x];
}
} else {
toReturn[i] = ob[i];
}
}
return toReturn;
};
它给出的输出如下:
var undesired_array = [
0. _index: "company",
0. _score: 1,
0. _source.ceo_name: "Tim Cook",
0. _source.city: "San Ramon",
0. _source.company_name: "Apple Inc.",
1. _id: "v2bdB5F3PbLzziayKikS",
1. _index: "company",
1. _score: 1,
1. _source.ceo_name: "Andrew N. Liveris",
1. _source.city: "New York",
1. _source.company_id: "v2bdB5F3PbLzziayKikS",
1. _source.company_name: "General Electric"
];
解决方案
考虑到每个对象中只有一层嵌套,这段代码应该可以工作。
function flattenObject(input) {
return input.map(function (doc) {
let flatDoc = {};
Object.keys(doc).forEach(function (key) {
if (doc[key]instanceof Object) {
Object.keys(doc[key]).forEach(function (innerkey) {
flatDoc[key + "_" + innerkey] = doc[key][innerkey];
});
} else {
flatDoc[key] = doc[key];
}
});
return flatDoc;
});
}
推荐阅读
- java - 如何在拦截器中获取控制器类名以进行日志记录
- access-token - Azure API 管理 - 如何刷新访问令牌后端 API?
- php - 无法从 XAMPP PHP 运行 Python 脚本
- perl - Perl - 需要明确的包名
- performance - 在 Torch 中计算频域卷积的更快替代方案
- python-3.x - 计算一个组合在日志中使用的次数
- python - 如何在 Django Rest Framework ViewSet 中使用 Last-Modified 标头?
- python - 如何从 AWS Lambda 提供 GIF、JPEG 和 PNG
- python-3.x - 告诉我如何通过 QUERY 从树莓派访问 OracleDB
- python - Image.fromarray() 正在制作 256 的矩阵 mod 中的每个元素