简体   繁体   中英

how to get a field from nested JSON in Javascript?

I want to take a field from nested JSON object as a string which is used as parameter.

I'm using a github project https://github.com/bencripps/react-redux-grid .

this react component is used for tree-grid.

I have a data and I want to map it as a tree-grid view.

My nested JSON object is below. It comes from an API. I want to take " 2020.total " as a parameter (line 4)

 "id": 1,
 "parentId": -1,
 "Name": "Category 1",
 "2020": {total:120, tax:12},
 "children": [{
                "id": 11,
                "parentId": 1,
                "Name": "Category 11",
                "2020":  {total:23, tax:2},
               
            }]

when i finally get this parameter i use it as a variable in below code (line 16)

  const complexData = {
    showTreeRootNode: false,
    data:datafromAPI,
    gridType: 'tree',
    dragAndDrop: true,
    columns: [
        {
            name: 'Name',
            className: 'additional-class',
            dataIndex: 'Name',
            sortable: false,
            expandable: true
        },
        {
            name: 'Total Payment',
            dataIndex: 2020.total,
            sortable: false,
            className: 'additional-class'
        }],
    
};

"Name" attribute is working fine but "Total Payment" is not working.

i tried those syntax;

'2020.total'
'[2020].total'
'[2020][total]'

I know this is a little bit syntax question but i don't know how to search for it.

thanks for all answer.

let a = {
"id": 1,
"parentId": -1,
"Name": "Category 1",
"2020": {total:120, tax:12},
"children": [{
     "id": 11,
     "parentId": 1,
     "Name": "Category 11",
     "2020":  {total:23, tax:2},             
   }]
}

Try a[2020].total

You can access it like this:

let a = {
  "2020": {total:120, tax:12},
}

a[2020].total
a["2020"].total

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