Skip to content
Advertisement

How do I compare an object property values to the values of an array, and then replace the object values with the array values?

Let’s say I have an array like this one (i’m adding random letters just to recreate my example a little better).

JavaScript

Then I have a group of objects.

JavaScript

As you can see my objects have different properties, but a lot of values match one or more values in my arr1. Now, for every value that mostly matches one of the strings in my arr1, I want to replace index of the matched value in arr1 into the object value (like shown below), for every object and for every property.

Example result:

JavaScript

What I’m actually trying to do in reality is to dynamically replace string values of libraries/technologies/frameworks/etc (i.e. “React”) from a portfolio project (the objects are fetched from a local json) with their respective icons (for that I’m using React icons). I don’t want to go edit the json directly.

I put all the icon components that I need in an array, then I used that to make a copy array with the “string” values of those icon components (array.map).

To get the index: I THINK it’s best to try and match arr1 one by one (“favorites”, “status”, and “gender” in this example), something like objects.map(object=>{object.favorites.includes("orangeaa").indexOf()} ??

Not all objects have a “favorites” property, so from that i will get some undefined results… Once I manage to get that index number, I will use it to render the actual icon. Since I’m using react, it will be something like this:

JavaScript

Advertisement

Answer

You could map the favorites with the indices of the target array.

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement