Skip to content
Advertisement

Dynamically get values of object from array

Let’s say I have an Object myBook and an array allCategories.

const allCategories = ["sciencefiction", "manga", "school", "art"];

const myBook = {
   isItScienceFiction: true,
   isItManga: false,
   isItForKids: false
}

What I want : Loop over categories to check the value of Book, for example, check if "sciencefiction" exists in my Book Object and then check it’s value

What I have tried :

1) With indexOf

allCategories.map((category) => {
    Object.keys(myBook).indexOf(category) 
    // Always returns -1 because "sciencefiction" doesn't match with "isItScienceFiction"
});

2) With includes

allCategories.map((category) => {
    Object.keys(myBook).includes(category) 
    // Always returns false because "sciencefiction" doesn't match with "isItScienceFiction"
});

Expected output :

allCategories.map((category) => {
   // Example 1 : Returns "sciencefiction" because "isItScienceFiction: true"
   // Example 2 : Returns nothing because "isItManga: false"
   // Example 3 : Returns nothing because there is not property in myBook with the word "school"
   // Example 4 : Returns nothing because there is not property in myBook with the word "art"


   // If category match with myBook categories and the value is true then
    return (
         <p>{category}</p>
    );
});

If you need more information, just let me know, I’ll edit my question.

Advertisement

Answer

You could use filter and find methods to return new array of categories and then use map method to return array of elements.

const allCategories = ["sciencefiction", "manga", "school", "art"];
const myBook = {isItScienceFiction: true, isItManga: false, isItForKids: false}

const result = allCategories.filter(cat => {
  const key = Object.keys(myBook).find(k => k.slice(4).toLowerCase() === cat);
  return myBook[key]
}).map(cat => `<p>${cat}</p>`)

console.log(result)

You can also use reduce instead of filter and map and endsWith method.

const allCategories = ["sciencefiction", "manga", "school", "art"];
const myBook = {isItScienceFiction: true,isItManga: false,isItForKids: false}

const result = allCategories.reduce((r, cat) => {
  const key = Object.keys(myBook).find(k => k.toLowerCase().endsWith(cat));
  if(myBook[key]) r.push(`<p>${cat}</p>`)
  return r;
}, [])

console.log(result)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement