Reputation: 290
I have this array structure :
var $obj = {
'sections1' : {
'row1' : {
'key1' : 'input1',
'key2' : 'inpu2'
},
'row2' : {
'key1' : 'input1',
'key2' : 'inpu2'
}
},
'sections2' : {
'row3' : {
'key1' : 'input1',
'key2' : 'inpu2'
},
'row4' : {
'key1' : 'input1',
'key2' : 'inpu2'
}
}
};
I want to fetch data from $obj->section2->row4->key2
. How can I make it using jquery and javascript both.
UPDATE: I want it to print the value in a paragraph or div
<p id="array"></p>
Upvotes: 0
Views: 817
Reputation: 121
Actually it looks quiet simple your requirement You can use the array notation or (.) dot operator
1) Array notation $obj['section2']['row4']['key2'];
2) Dot operator $obj.section2.row4.key2;
Nb: Please use array notation It would be safe in case of unknown keys if the key has a space in it
If you need it iterate through all the keys you can use for in loop
Upvotes: 1
Reputation: 5066
There are different ways. The best suited would be:
Bracket Notation
var prop = object['property_name'];
Dot Notation
var prop = object.property_name;
In your case it would be
var obj = {
'sections1' : {
'row1' : {
'key1' : 'input1',
'key2' : 'inpu2'
},
'row2' : {
'key1' : 'input1',
'key2' : 'inpu2'
}
},
'sections2' : {
'row3' : {
'key1' : 'input1',
'key2' : 'inpu2'
},
'row4' : {
'key1' : 'input1',
'key2' : 'inpu2'
}
}
};
console.log(obj.sections2.row4.key2);//Dot notation
console.log(obj['sections2']['row4']['key2']);//Bracket notation
document.getElementById("array").innerHTML=obj.sections2.row4.key2;
<p id="array"></p>
For more details refer MDN Property Accessors
Hoe it helps :)
Upvotes: 1
Reputation: 5546
In javascript use .
(dot) notation to access values
var obj = {
'sections1' : {
'row1' : {
'key1' : 'input1',
'key2' : 'inpu2'
},
'row2' : {
'key1' : 'input1',
'key2' : 'inpu2'
}
},
'sections2' : {
'row3' : {
'key1' : 'input1',
'key2' : 'inpu2'
},
'row4' : {
'key1' : 'input1',
'key2' : 'inpu2'
}
}
};
console.log(obj.sections2.row4.key2);
Upvotes: 1