skip to Main Content

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)?

2

Answers


  1. 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
    
    Login or Signup to reply.
  2. You should convert JSON to an object like this:

    const obj = JSON.parse('{"nog":{moves: number[][];}, "eyes":{moves: number[][]}}');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search