Home > Mobile >  How to get a json value with a dynamic key in js?
How to get a json value with a dynamic key in js?

Time:12-26

I have a json which I want to reference based on a variable:

matrix: {
    nog: {
        moves: number[][];
        scale: number;
    };
    eyes: {
        moves: number[][];
        scale: number;
    };
...

I have a variable art where art may be 'nog' or 'eyes' or ...

I would like to be able to extract data from the json with something like matrix.[art]

How might I do this (I could of course use a switch function, but looking for some thing more elegant that can scale)?

CodePudding user response:

You can just make use of matrix[art] pattern. E.g. below js code just works:

const matrix = {
    nog: {
        moves: [],
        scale: 1
    },
    eyes: {
        moves: [],
        scale: 2
    }}

let art = 'nog'
matrix[art].scale
1

let art = 'eyes'
matrix[art].scale
2

CodePudding user response:

You should convert JSON to an object like this:

const obj = JSON.parse('{"nog":{moves: number[][];}, "eyes":{moves: number[][]}}');
  • Related