Fill a empty value of a key-value pair with the next value of the next key.
myitems = {
'items1': [{first:true, second:false}, {first:true, second:true}],
'items2': [], //should be filled with {first:true, second:false}
'items3': [], //should be filled with {first:true, second:false}
'items4': [{first:true, second:false}, {first:true, second:true}],
'items5': [{first:false, second:true}],
'items6': [], //should be filled with {first:true, second:true}
'items7': [{first:true, second:true}],
}
I have tried the follow:
Object.entries(myItems).forEach(([key, value], index, values: any) => {
if (!values[index][1].length && values[index+1] && values[index+1][1].length) {
myItems[key] = [{...values[index + 1][1][0]}]
}
})
3
Answers
You should listen to the comments about the order of the keys in the object… But maybe the
reduceRight
method will help you somehow:Object properties order cannot be guaranteed. You should either use Array or Map. So I would rebuild the entire concept of what you’re trying to achieve.
Anyways, if you insist – for your specific example, an idea could be to use a temporary
next
variable that stores the last known next’s Object from the Array ofObject.values
, and use .reduceRight() or .reverse().forEach():But again this is a really bad idea.
Given the data object as you posted it, the order IS guaranteed.
Here is a solution in TypeScript
Typescript Playground
The output is
Here is the relevant MDN documentation on object property order
Note: If
myItems
final properties are empty arrays then they stay as empty arrays because there is nothing to set them with.