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
JavaScript
x
14
14
1
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" ]
2
3
function transformDataSources(datasource) {
4
const transformation = datasource.map(str => ({
5
sourceType: str.substr(0, str.indexOf("/")).split(" ").join(""),
6
policyReferences: [{
7
dataType: (str.match(/((.*))/).pop().split(" ").join(""))
8
}]
9
})).filter((item, index, array) => array.map(mapItem => mapItem.sourceType)
10
.indexOf(item.sourceType) === index)
11
console.log(transformation)
12
}
13
14
transformDataSources(datasources)
output:
JavaScript
1
12
12
1
[{
2
policyReferences: [{
3
dataType: "Metric"
4
}],
5
sourceType: "sourceType2"
6
}, {
7
policyReferences: [{
8
dataType: "Metric"
9
}],
10
sourceType: "sourceTYpe3"
11
}]
12
expected output:
JavaScript
1
31
31
1
[{
2
policyReferences: [
3
{
4
dataType: "Metric"
5
},
6
{
7
dataType: "Datamap"
8
},
9
{
10
dataType: "All"
11
},
12
{
13
dataType: "Event"
14
}
15
],
16
sourceType: "sourceType2"
17
}, {
18
policyReferences: [
19
{
20
dataType: "Metric"
21
},
22
{
23
dataType: "Event"
24
},
25
{
26
dataType: "Datamap"
27
},
28
],
29
sourceType: "sourceTYpe3"
30
}]
31
Advertisement
Answer
You need to group the items by sourceType
and collect dataType
for every group.
JavaScript
1
15
15
1
function transformDataSources(data) {
2
return Object.values(data.reduce((r, s) => {
3
const
4
sourceType = s.match(/^[^/]+/)[0],
5
dataType = s.match(/((.*))/)[1];
6
7
r[sourceType] ??= { sourceType, policyReferences: [] };
8
r[sourceType].policyReferences.push({ dataType });
9
return r;
10
}, {}));
11
}
12
13
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"]
14
15
console.log(transformDataSources(datasources));