Mapping two JavaScript objects and extracting values

I have two Objects:

"attributes": [
    {
      "trait_type": "Background",
      "value": "Black"
    },
    {
      "trait_type": "Eyeball",
      "value": "White"
    },
    {
      "trait_type": "Eye color",
      "value": "Yellow"
    },
    {
      "trait_type": "Iris",
      "value": "Small"
    },
    {
      "trait_type": "Shine",
      "value": "Shapes"
    },
    {
      "trait_type": "Bottom lid",
      "value": "Low"
    },
    {
      "trait_type": "Top lid",
      "value": "Middle"
    }

and

const traits = 
{
  "background": {
    "black": "20%",
    "red": "20%",
    "blue": "30%",
    "yellow": "10%",
    "white": "10%"
  },
  "eyeball": {
    "black": "15%",
    "red": "25%",
    "blue": "35%",
    "yellow": "5%",
    "white": "14%"
  }
}

How can I add a third key, value pair in "attributes" with key="rarity" and value = % after matching both trait_type and value in the traits object?

I know how I can do that fairly quickly in Python but I'm new to JavaScript and wonder what's the best and fastest way to solve this.


Solution 1:

You colud do something like:

let attributes = [ { "trait_type": "Background", "value": "Black" }, { "trait_type": "Eyeball", "value": "White" }, { "trait_type": "Eye color", "value": "Yellow" }, { "trait_type": "Iris", "value": "Small" }, { "trait_type": "Shine", "value": "Shapes" }, { "trait_type": "Bottom lid", "value": "Low" }, { "trait_type": "Top lid", "value": "Middle" } ]; 
const traits = { "background": { "black": "20%", "red": "20%", "blue": "30%", "yellow": "10%", "white": "10%" }, "eyeball": { "black": "15%", "red": "25%", "blue": "35%", "yellow": "5%", "white": "14%" } }; 

let result = attributes.map(attr => {
   return {
      "trait_type": attr.trait_type,
      "value": attr.value,
      "rarity": traits[attr.trait_type.toLowerCase()]?.[attr.value.toLowerCase()]
   } 
});

console.log(result);

Use map to create result array with new rarity key that looks for percentage value in traits object.