0

I have objects with different shapes and I want to access a part of it in a way that the caller can decide which part is needed.

In this example, I want to access a specific language which is stored in the object.

I implemented this function which works properly but isn´t there a better way to do this?

 
 texts: {  
    en: {
      one: "one",
      two: "two",
      three: "three"
    },
      de: {
      one: "eins",
      two: "zwei",
      three: "drei"
    },
    fr: {
      one: "un",
      two: "deux ",
      three: "trois"
    }, 
    es: {
      one: "uno",
      two: "dos",
      three: "tres"
    }
 }
}

function getPartialObj(obj, searchpath) {
  let returnvalue = undefined
  searchpath.forEach((value, index) => {
        for (const k in obj) {
          if (k === searchpath[index]) {
            console.log('found', k, "at index", index)
            obj = obj[k]
            if(index == searchpath.length - 1) {
              returnvalue = obj;
              break;
            }
          }
            });
   return returnvalue;
}

let searchpath  = ['texts', 'en']
const partialObj = getPartialObj(myTexts, searchpath)
if (partialObj !== undefined) {
    console.log("ready to work with ", partialObj);
}

Output: ready to work with { one: "one", three: "three", two: "two" }

A. L
  • 131
  • 2
  • 12

0 Answers0