If you take a look at the provided data object, it guarantees the order in which items are processed.
To tackle this in TypeScript, here's a solution:
const myItems: Record<string,{first:boolean, second:boolean}[]> = {
'items1': [{first:true, second:false}, {first:true, second:true}],
'items2': [], // need to add {first:true, second:false}
'items3': [], // need to add {first:true, second:false}
'items4': [{first:true, second:false}, {first:true, second:true}],
'items5': [{first:false, second:true}],
'items6': [], // need to add {first:true, second:true}
'items7': [{first:true, second:true}],
}
const arr: (keyof typeof myItems)[] =[];
for (let k in myItems) arr.push(k);
arr.reverse();
console.log(arr);
let last: {first:boolean, second:boolean} | undefined;
arr.forEach((k,ki)=>{
if (myItems[k].length===0){
if (last) myItems[k].push(last);
}
else {
last = myItems[k][0];
}
});
for (let k in myItems) {
console.log(k);
console.log(myItems[k][0]);
}
Explore TypeScript Playground
The resulting order is as follows:
[LOG]: ["items7", "items6", "items5", "items4", "items3", "items2", "items1"]
[LOG]: "items1"
[LOG]: {
"first": true,
"second": false
}
[LOG]: "items2"
[LOG]: {
"first": true,
"second": false
}
[LOG]: ... // more logs for each item
For additional information, refer to MDN documentation on object property orders
According to modern ECMAScript specifications, traversal order of properties within an object is consistent and well-defined. This includes iterating through keys both numerically and alphabetically.
Please note: If the final properties in myItems
end up as empty arrays, they will remain so as there is no content to replace them with.