I have an json array in format as below.
{
"agents": [{
"id": "1",
"first_name": "Stacy",
"last_name": "Thompson",
"fields": [{
"name": "workphone",
"values": {
"answer": "8888888888"
}
}, {
"name": "Industry",
"values": {
"answer": "computer"
}
}]
},
{
"id": "2",
"first_name": "Jhon",
"last_name": "Deo",
"fields": [{
"name": "workphone",
"values": {
"answer": "9999999999"
}
},
{
"name": "market",
"values": {
"answer": "Outer"
}
}
]
}
]
}
I want to convert it to a simpler array like below, so it will be easier to search :
{
"agents": [{
"id": "1",
"first_name": "Stacy",
"last_name": "Thompson",
"workphone": "8888888888",
"Industry": "computer"
}, {
"id": "2",
"first_name": "Jhon",
"last_name": "Deo",
"workphone": "9999999999",
"market": "Outer"
}]
}
I wrote the code as below , but I am getting error as
TypeError: Cannot set property 'id' of undefined
Here is the code:
let temp = response.data.agents;
let temparray=[];
for(let i = 0; i < temp.length; i++) {
let agent = temp[i];
Object.keys(agent).forEach(function(key) {
if(key=='fields'){
let tempfield = agent.fields;
for(let j = 0; j < tempfield.length; j++) {
let ccs = tempfield[j];
Object.keys(ccs).forEach(function(keys) {
if(keys=='name'){
temparray[i][ccs.name] = ccs.values.answer;
}
});
}
}
else{
temparray[i][key] = agent[key];
});
}
Array.prototype.pushinstead oftemparray[i]. The array doesn't have any elements.agentsarray in the object. That is an array.Array.mapis simple and powerful. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…