Home > Enterprise >  Map javascript object with array using lodash
Map javascript object with array using lodash

Time:05-06

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"]

CodePudding user response:

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)

  • Related