Response JSON:
[
[{
"name": "IMG00177.png",
"class": "Pore",
"confidence": "0.9",
"bbox": [160.0, 916.0, 169.0, 925.0],
"segmentation": []
},
{
"name": "IMG00177.png",
"class": "Pore",
"confidence": "0.81",
"bbox": [107.0, 890.0, 112.0, 896.0],
"segmentation": []
},
{
"name": "IMG00177.png",
"class": "Pore",
"confidence": "0.57",
"bbox": [119.0, 871.0, 123.0, 873.0],
"segmentation": []
},
{
"name": "IMG00177.png",
"class": "Pore",
"confidence": "0.63",
"bbox": [343.0, 703.0, 346.0, 705.0],
"segmentation": []
},
{
"name": "IMG00177.png",
"class": "Pore",
"confidence": "0.9",
"bbox": [337.0, 692.0, 345.0, 701.0],
"segmentation": []
}
],
[{
"name": "IMG00178.png",
"class": "Pore",
"confidence": "0.53",
"bbox": [1183.0, 1078.0, 1185.0, 1081.0],
"segmentation": []
},
{
"name": "IMG00178.png",
"class": "Pore",
"confidence": "0.83",
"bbox": [155.0, 1002.0, 161.0, 1008.0],
"segmentation": []
},
{
"name": "IMG00178.png",
"class": "Pore",
"confidence": "0.72",
"bbox": [107.0, 891.0, 111.0, 893.0],
"segmentation": []
},
{
"name": "IMG00178.png",
"class": "Pore",
"confidence": "0.77",
"bbox": [121.0, 871.0, 126.0, 873.0],
"segmentation": []
}
]
]
This is the response array for my api post request. i have a empty array and i want to check if the image name is same for another list. i want to parse that bbox value in list. Needed format:
[
{
"name":"1.png",
"confidence":[[0.9],[0.9],[0.9],[0.9],[0.9]],
"bbox":[[160.0, 916.0, 169.0, 925.0],[107.0, 890.0, 112.0, 896.0],[119.0, 871.0, 123.0, 873.0],[343.0, 703.0, 346.0, 705.0]]
}
]
I didn't have a clue how to iterate over this to get the required format.kindly guide me to approach this problem
CodePudding user response:
You can try the below code to get the required output. I have written captured each manipulation of the response in a separate variable for better understanding, but feel free to refactor to lesser lines of code. Do let me know if it fulfills your requirement.
const flatArray = [].concat.apply([], response);
const flatMap = flatArray.reduce((accum, e) => {
if (!accum[e.name]) {
accum[e.name] = {
name: e.name,
bbox: [e.bbox],
confidence: [[e.confidence]]
};
} else {
accum[e.name].confidence.push([e.confidence]);
accum[e.name].bbox.push(e.bbox);
}
return accum;
}, {});
console.log(Object.values(flatMap));
Snapshot of the console.