Home > Back-end >  How to access members of a nested object?
How to access members of a nested object?

Time:08-15

I have been trying to access the elements of a nested object but still have no success. I searched through existing similar questions on stackexchange (eg: this) but could not resolve my issue. I tried to access the final element using console.log(result.final) but it shows undefined in the console. Kindly advise.

var data = '{"response":{"valid":true,"final":{"message":" MS02","tags":{"d1":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzUxMiJ9","d2":"JhbGciOiJIUzI1NiJ9eyJ0eXAiOiJKV1QiLC","d3":"dupb9WWT8ypQYWw6QblkM98xFBBRsamkkWLw","d5":"5EChV1KJ4ASeh9crZDR3fivnSz4wCDmCr2RSC0CUrkx","d6":"hiH1I1SI3NHCYZeva0_FrjgSgxOa_YW6ECxRdAY-w5w","ua":"y"},"ti":"","op":[]}}}';
var dataJson = JSON.parse(data);
var result = [];

result = Object.entries(dataJson).map(([key, value]) => ({ [key]: value }))
console.log(result)
console.log(result.final)

CodePudding user response:

Use:

console.log(result[0].response.final)

Not a js developer so maybe somebody can provide better solution

CodePudding user response:

The OP's code, changed only to log correctly...

var data = '{"response":{"valid":true,"final":{"message":" MS02","tags":{"d1":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzUxMiJ9","d2":"JhbGciOiJIUzI1NiJ9eyJ0eXAiOiJKV1QiLC","d3":"dupb9WWT8ypQYWw6QblkM98xFBBRsamkkWLw","d5":"5EChV1KJ4ASeh9crZDR3fivnSz4wCDmCr2RSC0CUrkx","d6":"hiH1I1SI3NHCYZeva0_FrjgSgxOa_YW6ECxRdAY-w5w","ua":"y"},"ti":"","op":[]}}}';
var dataJson = JSON.parse(data);
var result = [];

result = Object.entries(dataJson).map(([key, value]) => ({ [key]: value }))
console.log(result)
console.log(result[0].response.final)

  • Related