I delete all duplicates by the “sourceType” property of the object in the array of objects, but I cannot copy the “dataType” property from the duplicates to the original, please check what I’ expecting in at output and expected output
const datasources = [ "sourceType2 /4 (Metric) Custom", "sourceType2 /4 (Datamap) Custom", "sourceType2 /4 (Event) Custom", "sourceType2 /4 (All) Custom", "sourceTYpe3 /4 (Metric) Custom", "sourceTYpe3 /4 (Datamap) Custom", "sourceTYpe3 /4 (Event) Custom" ]
function transformDataSources(datasource) {
const transformation = datasource.map(str => ({
sourceType: str.substr(0, str.indexOf("/")).split(" ").join(""),
policyReferences: [{
dataType: (str.match(/((.*))/).pop().split(" ").join(""))
}]
})).filter((item, index, array) => array.map(mapItem => mapItem.sourceType)
.indexOf(item.sourceType) === index)
console.log(transformation)
}
transformDataSources(datasources)output:
[{
policyReferences: [{
dataType: "Metric"
}],
sourceType: "sourceType2"
}, {
policyReferences: [{
dataType: "Metric"
}],
sourceType: "sourceTYpe3"
}]
expected output:
[{
policyReferences: [
{
dataType: "Metric"
},
{
dataType: "Datamap"
},
{
dataType: "All"
},
{
dataType: "Event"
}
],
sourceType: "sourceType2"
}, {
policyReferences: [
{
dataType: "Metric"
},
{
dataType: "Event"
},
{
dataType: "Datamap"
},
],
sourceType: "sourceTYpe3"
}]
Advertisement
Answer
You need to group the items by sourceType and collect dataType for every group.
function transformDataSources(data) {
return Object.values(data.reduce((r, s) => {
const
sourceType = s.match(/^[^/]+/)[0],
dataType = s.match(/((.*))/)[1];
r[sourceType] ??= { sourceType, policyReferences: [] };
r[sourceType].policyReferences.push({ dataType });
return r;
}, {}));
}
const datasources = ["sourceType2 /4 (Metric) Custom", "sourceType2 /4 (Datamap) Custom", "sourceType2 /4 (Event) Custom", "sourceType2 /4 (All) Custom", "sourceTYpe3 /4 (Metric) Custom", "sourceTYpe3 /4 (Datamap) Custom", "sourceTYpe3 /4 (Event) Custom"]
console.log(transformDataSources(datasources));