如何使用JavaScript将指定索引状态字符串转换为对应格式的Object对象
JavaScript处理索引状态字符串生成对象方案
核心思路
- 输入的字符串由表头行和数据行两部分组成,两行的字段顺序一一对应
- 先拆分出行,再把每行的连续空白替换为单个空格后拆分出字段,最后把表头字段和数据字段按位置配对生成对象
完整实现代码
function parseEsIndexStatus(str) { // 按换行拆分,过滤空行 const lines = str.split('\n').filter(line => line.trim() !== ''); // 处理表头行:替换连续空白为单个空格,拆分得到属性名数组 const keys = lines[0].replace(/\s+/g, ' ').trim().split(' '); // 处理数据行:同上操作得到值数组 const values = lines[1].replace(/\s+/g, ' ').trim().split(' '); // 拼接成对象 const result = {}; keys.forEach((key, index) => { result[key] = values[index]; }); return result; } // 测试用例 const inputStr = `health status index uuid pri rep docs.count docs.deleted store.size pri.store.size yellow open new_log jdbc1233q6AiRUSRCczayjz0rw 1 1 603442 0 127.6mb 127.6mb`; console.log(parseEsIndexStatus(inputStr));
输出结果
运行上述代码后,即可得到目标格式的对象:
{ "health": "yellow", "status": "open", "index": "new_log", "uuid": "jdbc1233q6AiRUSRCczayjz0rw", "pri": "1", "rep": "1", "docs.count": "603442", "docs.deleted": "0", "store.size": "127.6mb", "pri.store.size": "127.6mb" }
内容的提问来源于stack exchange,提问作者Soma
相关产品推荐
相关产品推荐

