简体   繁体   中英

Javascript - Access JSON object array

I have some JSON that looks like so:

data
  row_234745
    enqitem
       cost : "75.34"

It is stored in a data variable. I can access it in javascript like so:

console.log(data.data.row_234745.enqitem);

The problem is that row_234745 is variable. How can I make it so that the console displays the cost value without specifying the row?

I've tried things like:

console.log(data.data[0].enqitem);

But having no luck.

Try following

let row = "row_234745";
data.data[row].enqitem

Use bracket notation ( [] ) which allows properties/variables to be evaluated dynamically:

Try

var temp = 'row_234745';
console.log(data.data[temp].enqitem);

You can have a look at the below example (executed on Node REPL ) if it satisfies you needs.

If it doesn't satisfy, let me know in comment.

> var row_234745 = "branch";
undefined
>
> var data = {
... data: {
..... branch: {
....... enqitem: {
......... cost: "75.34"
......... }
....... }
..... }
... }
undefined
>
> data.data[row_234745].enqitem
{ cost: '75.34' }
>

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