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.
3 Answers 3
Try following
let row = "row_234745";
data.data[row].enqitem
answered Nov 8, 2018 at 9:58
Nikhil Aggarwal
28.5k4 gold badges46 silver badges61 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Use bracket notation ([]) which allows properties/variables to be evaluated dynamically:
Try
var temp = 'row_234745';
console.log(data.data[temp].enqitem);
answered Nov 8, 2018 at 9:58
Mamun
69k9 gold badges51 silver badges62 bronze badges
Comments
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' }
>
answered Nov 8, 2018 at 10:06
hygull
8,7382 gold badges47 silver badges55 bronze badges
Comments
lang-js
dataexactly as it is in your code in the question