简体   繁体   中英

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

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

You can just make use of matrix[art] pattern. Eg 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

you should convert Json to object like this: const obj = JSON.parse('{"nog":{moves: number[][];}, "eyes":{moves: number[][]}}');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM