am working on a task where I get a response consists of array of objects.
Now, I want to perform addition on some fields based on particular conditions and return new and unique array of objects without any duplicates.
Here is the response.
let respData = [
{
"NEW": 0,
"Working": 0,
"Not Working": 2,
"Broken": 0,
"Location": "Karimnagar",
"TotalPrice": 274500,
"AssetsCount": 2,
"AssetType": "Hardware Devices"
},{
"NEW": 1,
"Working": 0,
"Not Working": 0,
"Broken": 0,
"Location": "chennai",
"TotalPrice": 4500,
"AssetsCount": 1,
"AssetType": "Undefined"
},{
"NEW": 0,
"Working": 0,
"Not Working": 0,
"Broken": 0,
"Location": "Undefined",
"TotalPrice": 0,
"AssetsCount": 1,
"AssetType": "Undefined"
},{
"NEW": 1,
"Working": 0,
"Not Working": 0,
"Broken": 0,
"Location": "Karimnagar",
"TotalPrice": 12500,
"AssetsCount": 1,
"AssetType": "Hardware Devices"
},{
"NEW": 0,
"Working": 1,
"Not Working": 0,
"Broken": 0,
"Location": "Karimnagar",
"TotalPrice": 1200,
"AssetsCount": 1,
"AssetType": "Hardware Devices"
}
]
Now am trying to add the integer values in objects if AssetType
and Location
are same.
If there are not matching results present, need to return them as it is.
And after adding them, I need to return unique array of objects with all updated values.
I've tried with map
and filter
to get the result, but couldn't get the correct result.
This is the code I've tried.
let respCopy = respData;
let finalObj = {}, testArray = [];
respCopy.forEach((copyData, i) => {
respData.forEach((data, j) => {
if(i !== j && copyData.AssetType === data.AssetType && copyData.Location === data.Location){
assetConditions.forEach((condition, k) => {
if(copyData[condition.name]){
finalObj[condition.name] = copyData[condition.name] + data[condition.name];
finalObj["AssetType"] = copyData.AssetType;
finalObj["Location"] = copyData.Location;
copyData[condition.name] = 0;
data[condition.name] = 0;
}
})
}else if(i == j && copyData.AssetType === data.AssetType && copyData.Location === data.Location){
assetConditions.forEach((condition, k) => {
if(copyData[condition.name]){
finalObj[condition.name] = copyData[condition.name];
finalObj["AssetType"] = copyData.AssetType;
finalObj["Location"] = copyData.Location;
copyData[condition.name] = 0;
data[condition.name] = 0;
}
})
}
});
testArray.push(finalObj);
})
This is the expected result.
[
{
"NEW": 1,
"Working": 1,
"Not Working": 2,
"Broken": 0,
"Location": "Karimnagar",
"TotalPrice": 288200,
"AssetsCount": 4,
"AssetType": "Hardware Devices"
},{
"NEW": 1,
"Working": 0,
"Not Working": 0,
"Broken": 0,
"Location": "chennai",
"TotalPrice": 4500,
"AssetsCount": 1,
"AssetType": "Undefined"
},{
"NEW": 0,
"Working": 0,
"Not Working": 0,
"Broken": 0,
"Location": "Undefined",
"TotalPrice": 0,
"AssetsCount": 1,
"AssetType": "Undefined"
}
]
Code I've tried in Codepen
Is there anything am making mistakes in getting the result?