我有一个格式如下的 json 数组。
{
"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"
}
}
]
}
]
}
我想将它转换为一个更简单的数组,如下所示,这样搜索起来会更容易:
{
"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"
}]
}
我编写了如下代码,但出现错误
TypeError: Cannot set property 'id' of undefined
这是代码:
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];
});
}