Iterate over array of objects

Posted on
  • How to write this correct?

    var replaceList  = { 
      yyyy: "d.getFullYear()", 
      yy:   "d.getFullYear().substr(-2)",
      mm:   "('0'+d.getMonth()).substr(-2)",
      dd:   "('0'+d.getDay()).substr(-2)",
      d:    "d.getDay()",
      m:    "d.getMonth()",
      HH:   "('0'+d.getHours()).substr(-2)",
      MM:   "('0'+d.getMinutes()).substr(-2)",
      SS:   "('0'+d.getSeconds()).substr(-2)",
      //.... and more 
    };
    
    // create time normal 
    var timePattern =  { 0: "HH:MM:SS ", 1: "HH:MM" };
    var timeN =  timePattern[0];
    replaceList.forEach(e => {
      timeN = timeN.replace(e,replaceList[e]);
    });
    console.log(timeN);
    
    
  • I think Object.keys will do you:

    Object.keys(replaceList).forEach(e => {
      timeN = timeN.replace(e,replaceList[e]);
    });
    
  • Thanks, it works

    console.log(timeN);
    ('0'+d.getHours()).substr(-2):('0'+d.get­Minutes()).substr(-2):('0'+d.getSeconds(­)).substr(-2)

  • Quite interesting... this logic pulls it of 'the other way round'... which may become a performance challenge when the replaceList being larger and larger compared to the pattern elements...

  • which may become a performance challenge

    It'll definitely get slower, however in this case we're actually doing the work on the PC before upload to the Bangle.js, so I don't think it'll be that big a deal for us. On Bangle.js itself this could be a complete pain though.

  • Ic... it is a one-time-thing of composing/generating the code before uploading it... as source?

  • That's the idea :)

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

Iterate over array of objects

Posted by Avatar for MaBe @MaBe

Actions