You can use a for ... in loop to loop through the object, and build a new object from the original.
function flipObj( i ) {
// If the input variable is not an object, fail.
if( typeof i !== "object" ) return false;
// If the input object is empty, fail
if( Object.keys( i ).length === 0 ) return false;
// Create an empty object.
o = {};
// Loop through the dates
for( var d in i ) {
// If the property in question is not an object, skip it.
if( typeof i[d] !== "object" ) continue;
// If the property is empty, skip it.
if( Object.keys( i[d] ).length === 0 ) continue;
// Loop through the email addresses
for( var e in i[d] ) {
// If there is no property in our created object for the email, make one
if(!o[e]) o[e] = { days: [], id: i[d][e] };
// Push the day into the days array for the email object in question.
o[e].days.push( d );
}
}
// If our new object is empty, fail
if( Object.keys( o ).length === 0 ) return false;
// Return our new object.
return o;
}
// Works
console.log( flipObj( { '2015-08-09': { '[email protected]': 5, '[email protected]': 4, '[email protected]': 6 }, '2015-09-09': { '[email protected]': 5, '[email protected]': 4, '[email protected]': 6, '[email protected]': 4 }, '2015-10-09': { '[email protected]': 5, '[email protected]': 4, '[email protected]': 6, '[email protected]': 10, '[email protected]': 7 } } ) );
// Fails
console.log( flipObj( {} ) );
// Fails
console.log( flipObj( { 'hello': 'world' } ) );
The following is the output from the above script
[object Object] {
[email protected]: [object Object] {
days: ["2015-08-09", "2015-09-09", "2015-10-09"],
id: 4
},
[email protected]: [object Object] {
days: ["2015-08-09", "2015-09-09", "2015-10-09"],
id: 6
},
[email protected]: [object Object] {
days: ["2015-10-09"],
id: 7
},
[email protected]: [object Object] {
days: ["2015-09-09", "2015-10-09"],
id: 4
},
[email protected]: [object Object] {
days: ["2015-08-09", "2015-09-09", "2015-10-09"],
id: 5
}
}
false
false
As you can see we now have an object for each email address containing an array of the days and the id.