0

This line: let X = this.appGlobal.GetNavigationLanguage().data; retuns JSON as you can see below.

I want to take NAV.REPORTS.BMAIL.TITLE.

Translate code (NAV.REPORTS.BMAIL.TITLE) is dynamically created.

  1. X.NAV.REPORTS.BMAIL.TITLE => works
  2. X['NAV']['REPORTS']['BMAIL']['TITLE'] => works

But keep in mind I have dynamically created translation code I need something like this:

let transCode = 'NAV.REPORTS.BMAIL.TITLE';
console.log(X[transCode]);

How I can achieve this?

2
  • Can you split the transCode by a . separator and then pick off the indeces as needed? If you're using other libraries, there are some good functions, like ramdajs.com/docs/#path. Commented Nov 28, 2018 at 14:24
  • I can but in that case, I must use double for iteration because every one item of navigation can have children. So I want to avoid that. Commented Nov 28, 2018 at 14:28

2 Answers 2

2

test_data = {
  NAV: {
    REPORTS: {
      BMAIL: {
        TITLE: "hello"
      }
    }
  }
}

let transCode = 'NAV.REPORTS.BMAIL.TITLE';
properties = transCode.split('.'); //--> ["NAV","REPORTS","BMAIL","TITLE"]

result = test_data
properties.forEach(function(property) {
  result = result[property]
})

console.log(result) // --> hello

Sign up to request clarification or add additional context in comments.

1 Comment

This is a neat solution.
1

The short and evil route would be the following:

console.log(eval(`X.${transCode}`));

The less evil way is to use a recursive function call, this means you only look into the number of items in your string-path (rather than looping the whole collection).

const X = {
    NAV: {
        REPORTS: {
            BMAIL: {
                TITLE: 'Test'
            }
        }
    }
}


const transCode = 'NAV.REPORTS.BMAIL.TITLE';

// Evil...
console.log(eval(`X.${transCode}`));  // Test

// Less Evil (but needs exception handling)...
function getData(input: any, splitPath: string[]) {
    const level = splitPath.pop();

    if (splitPath.length === 0) {
        return input[level];
    } else {
        return getData(input[level], splitPath);
    }
}

const result = getData(X, transCode.split('.').reverse());

console.log(result); // Test

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.