Map javascript object with array using lodash

I am new using lodash and I would like to solve the following scenario in a clean way using lodash instead a for statement.

The array "data" should be used to search in the JS object "Categories" to find each element, return the value and generate an array as is shown in the code below. #If the array contain a element that doesn't exist in the JS object, it should return a default value.

var categories = {
  "A" : "LOW",
  "B" : "LOW",
  "C" : "MEDIUM",
  "D" : "MEDIUM",
  "E" : "HIGH"
}

var data = ["A", "B", "C", "Unexpected"]

var defaultValue = "VERYLOW"



expected result:
["LOW", "MEDIUM", "VERYLOW"]

1 answer

  • answered 2022-05-05 21:55 Kinglish

    This isn't what you asked for, but Lodash is just an abstraction for vanilla JS. For what it's worth, this is pretty clean (and doesn't use for-in)

    [...new Set(data.reduce((b,a) => ([...b, categories[a] ?? defaultValue]),[]))]
    

    let categories = { "A" : "LOW", "B" : "LOW", "C" : "MEDIUM", "D" : "MEDIUM", "E" : "HIGH" }
    let data = ["A", "B", "C", "Unexpected"], defaultValue = "VERYLOW"
    
    let result = [...new Set(data.reduce((b,a) => ([...b, categories[a] ?? defaultValue]),[]))]
    
    console.log(result)

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum