Home > Software engineering >  Javascript - how do I compare an object property values to the values of an array, and then replace
Javascript - how do I compare an object property values to the values of an array, and then replace

Time:05-11

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

arr1 = ["appless", "bananarr", "orangeaa", "coconutvv", "pineapplevv"]

then I have a group of objects

const objects: [{
name: "john", 
job: "carpenter",
color: "blue"
status: "banana"},

{
name: "john", 
job: "plumber",
favorites: "banana", "apple", "orange",
color: "blue", "purple"},

{
name: "john", 
job: "carpenter",
favorites: "orange", "pineapple",
gender: "female"}]

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:

const objects: [{
name: "john", 
job: "carpenter",
color: "blue"
status: 1},

{
name: "john", 
job: "plumber",
favorites: 1, 0, 2,
color: "blue", "purple"},

{
name: "john", 
job: "carpenter",
gender: "female", 2}]

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

{object.favorites && (<div>
<h3>Favs:</h3>{object.favorites.map(i=><p key={i}>{iconComponentsArray[i]}</p>)}

I hope I am clear enough! Thank you!

CodePudding user response:

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

function getIndices(values, targets) {
    return values.map(s => targets.findIndex(t => t.includes(s)));
}

console.log(getIndices(
    ["banana", "apple", "orange"],
    ["appless", "bananarr", "orangeaa", "coconutvv", "pineapplevv"]
));

  • Related