Search code examples
javascriptlodash

Filter object and turn it to Array of Objects with Lodash


Is it possible that separate object key/values, then filter specific characters, then return a new Array of Objects like this: const object = { id-0: 12, id-1:19 volume-0: 13, volume-1: 10, price-0: 9, price-1: 19 }

then I need this array:

const newArray = [ { id:12 volume: 13, price: 9 }, { id:19 volume: 10, price: 19 } ]


Solution

  • Get the object's entries, reduce them to a Map (see comments in code), and then convert back to an array using Array.from():

    const object =  { 'id-0': 12, 'id-1':19, 'volume-0': 13, 'volume-1': 10, 'price-0': 9, 'price-1': 19 }
    
    
    const result = Array.from(
      Object.entries(object)
        .reduce((acc, [mixedKey, value]) => {
          const [prop, key] = mixedKey.split('-') // get the key and the object's name
    
          if(!acc.has(key)) acc.set(key, {}) // add new object to the key if none exists
    
          acc.get(key)[prop] = value // add the prop value to the object
    
          return acc
        }, new Map())
        .values()
    )
      
    console.log(result)

    Using lodash, convert to entries using _.toPairs(). Map the array of entries to an array of objects in the shape of { 0: { id: 12 }. Merge all objects to a single object, and convert to an array using _.values():

    const { flow, toPairs, map, merge, values } = _
    
    const fn = flow(
      toPairs,
      pairs => map(pairs, ([k, v]) => {
        const [prop, key] = k.split('-')
        
        return { [key]: { [prop]: v }}
      }),
      arr => merge(...arr),
      values
    )
    
    const object =  { 'id-0': 12, 'id-1':19, 'volume-0': 13, 'volume-1': 10, 'price-0': 9, 'price-1': 19 }
    
    
    const result = fn(object)
    
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>