简体   繁体   中英

Merge json response with Same id with different data in Node js

I am getting a JSON array as a response for my API I would like to merge an array of JSON response with the same id into a single JSON object

Example

[
{
   "id": 1,
   "emp_name": "ram",
   "department": "IT",
   "hours": 127,
   "projectcode": "IKTXXX"
},
{
   "id": 1,
   "emp_name": "ram",
   "department": "CS",
   "hours": 67,
   "projectcode": "IKTXXY"
},
{
   "id": 1,
   "emp_name": "ram",
   "department": "ES",
   "hours": 52,
   "projectcode": "IKTXYY"
},
{
   "id": 2,
   "emp_name": "Sam",
   "department": "CS",
   "hours": 100,
   "projectcode": "IKTXXZ"
}
]

The desired result I need is

[
{

   "id": 1,
   "emp_name": "ram",
   "department": "IT$127$IktXXX, CS$67$IKTXXY, ES$52$IKTXYY"
},
{

   "id": 2,
   "emp_name": "Sam",
   "department": "CS$100$IKTXXZ"
}
]

Can I know how to do like this in node using underscore library or using brute force method

We can use Array.reduce to create an object map of entries keyed by id.

For each entry in the map, we use the id and emp_name of each row, then append the appropriate department to the department string of that entry.

Once we have this, we can use Object.values to get an Array of these entries:

 const input = [ { "id": 1, "emp_name": "ram", "department": "IT", "hours": 127, "projectcode": "IKTXXX" }, { "id": 1, "emp_name": "ram", "department": "CS", "hours": 67, "projectcode": "IKTXXY" }, { "id": 1, "emp_name": "ram", "department": "ES", "hours": 52, "projectcode": "IKTXYY" }, { "id": 2, "emp_name": "Sam", "department": "CS", "hours": 100, "projectcode": "IKTXXZ" } ] const mapById = input.reduce((acc, { id, emp_name, department, hours, projectcode }) => { acc[id] = { id, emp_name, department: (acc[id]? acc[id].department + ", ": "") + `${department}$${hours}$${projectcode}`} return acc; }, {}) const resultArray = Object.values(mapById); console.log("Output:", resultArray)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM