Have ideas to improve npm?Join in the discussion! »

    object-forof

    1.5.2 • Public • Published

    NPM Build Status

    Object forOf

    Simple object iterator

    Install

    npm install object-forof --save

    example

    const forOf = require('object-forof')
     
                      // Explanation:
    const obj = {
      input: {        // --> type
        in1:          // --> port
          '1',        // --> val
                      // Calls: fn('input', 'in1', '1')
     
        in2:          // --> port
          '2'         // --> val
                      // Calls: fn('input', 'in1', '2')
      },
      output: {       // --> type
        out1:         // --> port
          '1',        // --> val
                      // Calls: fn('output', 'out1', '1')
     
        out2:         // --> port
          '2'         // --> val
                      // Calls: fn('output', 'out2', '2')
      }
    }
     

    Given the above example you could use Object.keys like this:

    Object.keys(obj).forEach((type) => {
      Object.keys(obj[type]).forEach((port) => {
        const val = obj[type][port]
        // do something with type, port, val
      })
    })

    Or a for in loop

    for (let type in obj) {
      if (obj.hasOwnProperty(type)) {
        for (let port in obj[type]) {
          if (obj[type].hasOwnProperty(port)) {
            const val = obj[type][port]
            // do something with type, port, val
          }
        }
      }
    }

    With forOf:

    forOf((type, port, val) => {
      // do something with type, port, val
     
      // optionally return something
    }, obj)

    If you return something other from the function than undefined it will be added as a value within the returned array.

    E.g.

    forOf((type, port, val) => (
      type === 'input' ? {type: type, val: val} : undefined
    ), obj)
    forOf((type, port, val) => ({type: type, val: val}), obj)
      .filter((val) => {
      return val.type === 'input'
    })

    Both result in:

      [
       {type: 'input', val: '1'},
       {type: 'input', val: '2'}
      ]
     

    Download

    Keywords

    none

    Install

    npm i object-forof

    DownloadsWeekly Downloads

    17

    Version

    1.5.2

    License

    MIT

    Last publish

    Collaborators

    • avatar