Reputation: 55200
I have this JSON
{
"Entries": [{
"JobId": 7322,
"DayOfTheWeek": "Wednesday",
"Punchouts": ["2016-05-05T09:50:00", "2016-05-05T12:20:00"],
"PunchIns": ["2016-05-05T10:10:00", "2016-05-05T12:40:00"]
}, {
"JobId": 7322,
"DayOfTheWeek": "Thursday",
"Punchouts": ["2016-05-05T09:50:00"],
"PunchIns": ["2016-05-05T09:40:00"]
}]
}
I would change it to
{
"Entries": [{
"JobId": 7322,
"DayOfTheWeek": "Wednesday",
"Punchout1": "2016-05-05T09:50:00",
"Punchout2": "2016-05-05T12:20:00",
"PunchIn1": "2016-05-05T10:10:00",
"PunchIn2": "2016-05-05T12:40:00"
}, {
"JobId": 7322,
"DayOfTheWeek": "Thursday",
"Punchout1": "2016-05-05T09:50:00",
"Punchout2": "",
"PunchIn1": "2016-05-05T09:40:00"
"PunchIn2": "",
}]
}
I would like to condense the array. The array will have max length = 2. Even if the length is 0 / 1, the array should have empty string for PunchOut1/PunchOut2 and PunchIn1/PunchIn2
Implemented it like this.
for (var i = 0; i < data.Entries.length; i++) {
var entry = data.Entries[i];
if (entry["Punchouts"].length == 0) {
entry["PunchOut1"] = "";
entry["PunchOut2"] = "";
}
if (entry["Punchouts"].length == 1) {
entry["PunchOut1"] = entry["Punchouts"][0];
entry["PunchOut2"] = "";
}
if (entry["Punchouts"].length == 2) {
console.log("in");
entry["PunchOut1"] = entry["Punchouts"][0];
entry["PunchOut2"] = entry["Punchouts"][1];
}
delete entry["Punchouts"];
// do same for PunchIns.
}
Fiddle: https://jsfiddle.net/codeandcloud/rpgx28gy/
What would be a more optimized (preferably lodash) way?
Upvotes: 0
Views: 61
Reputation: 7858
var remappedEntries = _.map(data.Entries, e => ({
JobId: e.JobId,
DayOfTheWeek: e.DayOfTheWeek,
PunchOut1: e.PunchOuts[0] || "",
PunchOut2: e.PunchOuts[1] || "",
PunchIn1: e.PunchIns[0] || "",
PunchIn2: e.PunchIns[1] || "",
}));
This uses lodash's map, which iterates through every value and gives you an iteratee function that you can use to re-map that entry to another object. Note that you don't need to use lodash at all for this, you can use the Array.prototype.map
function, assuming the browsers you aim for support it. There are also shims that you can use.
If instead of getting a copy you want to modify the exact same object, you can use _.forEach
, or keep using map and discard the previous object. Really depends on your case.
I've also used arrow functions which make it simpler, from every "e" to the object that you want to return. Alternatively, this could be a named or an anonymous function that takes one parameter.
For each punchout, I'm taking advantage that you can check an array even if it doesn't have an object there. In that case, it'll return undefined. For those, we default them to empty string by using the conditional or, because undefined is considered "falsy" and so that expression will return the empty string. If it had a value, it'd use that one.
Upvotes: 1