Home > Net >  replace json key with another json value using node js / javascript
replace json key with another json value using node js / javascript

Time:02-12

testDetails.map(function(data){
 
let JsonData={
 title: data["title"],
 url: data["url"],
 firstName: data["username"],

 work:[{workid:data["workid"].slice(","), workname: "tester"}],
 employee: [{employee_id: data["employee_id"].slice(","), employee_desk:"custom"}]
}
})

so my above json output look like this

{
 "title":"01"
 "url":"[email protected]",
 "firstName":"employee name",
 "work":[{"workid":"9371", "workname": "tester"}],
 "employee":[{"employee_id":"weh34",employee_desk:"custom"}]
}

and another JSON object where data look like this

let data={
  "031w":"ewid3728e",
  "9371":"emp_01",
   "weh34":"work_place01"
}

The workid and employee id with the JsonData I want to replace with the value which is present inside the data json so my data which is look like this

 "work":[{"workid":"9371", "workname": "tester"}],
 "employee":[{"employee_id":"weh34",employee_desk:"custom"}]

needed to be look like this

 "work":[{"workid":"work_place01", "workname": "tester"}],
 "employee":[{"employee_id":"emp_01",employee_desk:"custom"}]

I am trying to replace the code manually like this

 work:[{workid:data.weh34, workname: "tester"}],
 employee: [{employee_id: data.9371, employee_desk:"custom"}]

but data["workid"].slice(",") and data["employee_id"].slice(",") always get changed so I want to match both the json and fetch the value and place it in my JsonData

CodePudding user response:

Just use the value you got from testDetails as the index in the data object to get the corresponding value.

You need to use a different variable from data as the parameter to the mapping function so you can refer to the external variable data. I changed it to d below.

testDetails.map(d => ({
  title: d["title"],
  url: d["url"],
  firstName: d["username"],
  work: [{
    workid: data[d["workid"].slice(",")],
    workname: "tester"
  }],
  employee: [{
    employee_id: data[d["employee_id"].slice(",")],
    employee_desk: "custom"
  }]
}));
  • Related