Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

iterate through an object sugarcube 2

I know how to iterate through arrays with for loops, but is it possible to do it with objects such as?
<<set $char={
	stats:{
		health:{name:"health",val:90,max:100,min:0,type:0},
		mana:{name:"mana",val:10,max:50,min:0,type:0},
		str:{name:"str",val:8,max:10,min:0,type:0},
		int:{name:"int",val:2,max:10,min:0,type:0}
	},
	desc:{
		name:{name:"name",val:"bob"},
		age:{name:"age",val:29}
	}
}>>

How can you iterate through that object and get the val for all of the objects in stats for example? I have tried using Object.keys, but once i get the name of the object i am stuck.

Thanks

Comments

  • was just playing around, and figured it out. not sure if its the best way but here is a quick way to print out all the vals under stats. not sure if its the most efficient or best way.
    <<for $x=0;$x<Object.keys($char.stats).length;$x++>>
    
    <<print $char.stats[Object.keys($char.stats)[$x]].val>>
    
    <</for>>
    
  • edited March 2017
    Hmm, that's a pretty nice data structure to hold RPG game values. Thanks for posting that!
  • Try something like the following, it uses Object.key to get the name of each of the child properties (stats), then loops while using that name to retrieve the related child object, and the value of it's val property. The code also uses temporary variables
    <<set _stats to Object.keys($char.stats)>>
    <<for _i = 0; _i < _stats.length; _i++>>
    	<<print $char.stats[_stats[_i]].val>>
    <</for>>
    
  • edited March 2017
    was just playing around, and figured it out. not sure if its the best way but here is a quick way to print out all the vals under stats. not sure if its the most efficient or best way.
    <<for $x=0;$x<Object.keys($char.stats).length;$x++>>
    
    <<print $char.stats[Object.keys($char.stats)[$x]].val>>
    
    <</for>>
    
    Issues:
    • You're generating the list of properties twice per each iteration of the loop. You, generally, only need to do that once, total.
    • Unless you need the loop variables to persist, use temporary variables, not story variables.
    For example:
    <<for _i to 0, _statNames to Object.keys($char.stats); _i lt _statNames.length; _i++>>
    	<<print $char.stats[_statNames[_i]].val>>
    <</for>>
    
Sign In or Register to comment.