JSFiddle - React, Tailwind, and code Playground
by thakkar
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
JavaScript
var modems =
[
{
"id":2,
"name":"Modem 1",
"powerUserOffer":1,
"telcoMetadata":[
{
"id":181,
"name":"Naked ADSL 100"
},
{
"id":182,
"name":"Double Play 100"
},
{
"id":186,
"name":"Double Play No Data Cap"
}
],
"telcoMetadataIds":[
180,
181,
182,
186
]
},
{
"id":3,
"name":"Modem 2",
"powerUserOffer":2,
"telcoMetadata":[
{
"id":180,
"name":"Naked ADSL No Data Cap"
},
{
"id":181,
"name":"Naked ADSL 100"
},
{
"id":182,
"name":"Double Play 100"
},
{
"id":186,
"name":"Double Play No Data Cap"
}
],
"telcoMetadataIds":[
180,
181,
182,
186
]
}
];
/*
var telcoPlans = _.map(data, function(modem) {
return _.map(modem.telcoMetadata, function(tp){
return tp.name;
});
});
var uniqueTelcoPlans = _.unique(_.flatten(telcoPlans));
var tpModems = _.
console.log(uniqueTelcoPlans);
*/
var telcoMetadataIndexed = {};
var telcoMetadata = [];
modems.forEach(function(product) {
product.telcoMetadata.forEach(function(tMetadata) {
// create a new tMetadata if it does not exist yet
if(!telcoMetadataIndexed[tMetadata.id]) {
telcoMetadataIndexed[tMetadata.id] = {
id: tMetadata.id,
name: tMetadata.name,
modems: []
};
telcoMetadata.push(telcoMetadataIndexed[tMetadata.id]);
}
// add the product to the tMetadata
telcoMetadataIndexed[tMetadata.id].modems.push({
id: product.id,
name: product.name
});
});
});
console.log(telcoMetadata);