简体   繁体   中英

How can I fetch values from object array using jquery and javascript

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>

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

There are different ways. The best suited would be:

  1. Bracket Notation

    var prop = object['property_name'];

  2. 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 :)

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

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