0

I have json string and want to get a value by key, but key name is value of some variable. To resolve the issue I've found this

window[varName]

and tried to use as following

<script>
var jsonStr = '{"someProperty":"Value of someProperty","somePropertyAndSuffix":"Value of somePropertyAndSuffix"}';
var jsonObj = JSON.parse(jsonStr);

var propAsString = 'someProperty';

console.log(jsonObj.window[propAsString]);
console.log(jsonObj.window[propAsString]+'AndSuffix');
</script>

but I get the error

Uncaught TypeError: Cannot read property 'someProperty' of undefined

If I try

console.log(jsonObj[window[propAsString]]);
console.log(jsonObj[window[propAsString]+'AndSuffix']);

I get two undefined

3
  • 1
    Why do you have window in there? Commented Dec 26, 2018 at 18:26
  • 1
    First of all, window property is not defined in jsonObj. 2nd, you should do jsonObj[propAsString + 'AndSuffix'] Commented Dec 26, 2018 at 18:26
  • If you know jsonObj and propAsString are defined, you can just do jsonObj[propAsString] Commented Dec 26, 2018 at 18:28

2 Answers 2

2

Remove window and it will work. jsonObj would be accessible on window (window.jsonObj) as javascript is hoisting the assignments with var to the closest scope (in this case the window).

var jsonStr = '{"someProperty":"Value of someProperty","somePropertyAndSuffix":"Value of somePropertyAndSuffix"}';
var jsonObj = JSON.parse(jsonStr);

var propAsString = 'someProperty';

console.log(jsonObj[propAsString]);
console.log(jsonObj[propAsString + 'AndSuffix']);

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

Comments

2

I'm not sure if I correctly understand this, but this is how to solve this:

const jsonStr = '{"someProperty":"Value of someProperty","somePropertyAndSuffix":"Value of somePropertyAndSuffix"}'
const obj = JSON.parse(jsonStr)
const propAsString = 'someProperty'
console.log(obj[propAsString], obj[propAsString + 'AndSuffix'])

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.