0

I have a function within NodeJS which is returning an array of JSON elements

let rows = function1();

Here rows look like:

"rows": [
    {
    "Hostname": "abc123",
    "name": "name1",
    "Status": "PASS",
    "Heading": "Not Applicable"
    },
    {
    "Hostname": "abc123",
    "name": "name2",
    "Status": "FAIL",
    "Heading": "Not Applicable"
    }
]

Here, rows can have any number of Json elements:

"rows": [
    {
    "Hostname": "abc123",
    "name": "name1",
    "Status": "PASS",
    "Heading": "Not Applicable"
    },
    {
    "Hostname": "abc123",
    "name": "name2",
    "Status": "FAIL",
    "Heading": "Not Applicable"
    },
    {
    "Hostname": "abc123",
    "name": "name3",
    "Status": "FAIL",
    "Heading": "Not Applicable"
    },
 ...
]

In all JSON elements Hostname will remain name,

I want to modify the rows array such that it looks as below:

"rows": [
    {
    "Hostname": "abc123",
    "name1Status": "PASS",
    "name1Heading": "Not Applicable"
    "name2Status": "FAIL",
    "name2Heading": "Not Applicable"
    "name3Status": "FAIL",
    "name3Heading": "Not Applicable"
     ...
]

1 Answer 1

1

If you understand correctly, then you need to achieve this result. Use reduce for this, very convenient for working with arrays

const rows = [
    {
    "Hostname": "abc123",
    "name": "name1",
    "Status": "PASS",
    "Heading": "Not Applicable"
    },
    {
    "Hostname": "abc123",
    "name": "name2",
    "Status": "FAIL",
    "Heading": "Not Applicable"
    }
]
const res = rows.reduce((acc, rec) => {
	let result = { ...acc, [`Hostname`]: rec.Hostname,  [`${rec.name}Status`]: rec.Status, [`${rec.name}Heading`]: rec.Heading  }
	return result
}, [])
console.log(res)

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

2 Comments

Here, the output is not showing "Hostname": "abc123". Instead it is showing "abc123": "abc123"
Yes, sry. try now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.