-3

Could you please help me to prepare below Object from string using JS. I am new in JS.

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

From above string how do I create below object?

{
    "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"
}
3

1 Answer 1

1

Here is how you can use split

const str = `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`
const lines = str.split(/\n/); // split lines on \n
const arrs = lines.map(line => line.split(/\s+/)); // split line on whitespace
const obj = {}; // define an object, we could use reduce but this is easier to read
arrs[0].forEach((word,i) => obj[word] = arrs[1][i])
console.log(obj); // show it
console.log(JSON.stringify(obj)); // show the JSON

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for editing my question, however @mplungjan, till I don't understand why did my question is being as mark as negative?
@Soma Because you did not show any effort in fixing the issue yourself. Read the How to Ask to see how
Okay, got it. Actually my code is around 2000 lines. And one of line I was getting that string as ES response which I need to display in Nebular Tabular format. Henceforth was not sure how much should I post with you. For a clean approach I was going for this. Anyway thanks for the help.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.