如何使用 jquery 和 javascript 从对象数组中获取值

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

我有这个数组结构:

var $obj = {
        'sections1' : {
            'row1' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            },
            'row2' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            }
        },
        'sections2' : {
            'row3' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            },
            'row4' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            }
        }
    };

我想从 $obj->section2->row4->key2 获取数据。我怎样才能同时使用 jquery 和 javascript。

更新:我希望它打印段落中的值或 div

<p id="array"></p>

在 javascript 中使用 .(点)表示法访问值

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

有不同的方法。最适合的是:

  1. 括号表示法

    var prop = object['property_name'];

  2. 点符号

    var prop = object.property_name;

你的情况是

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>

有关详细信息,请参阅 MDN Property Accessors

锄它有帮助:)

其实你的要求看起来很简单 您可以使用数组符号或 (.) 点运算符

1) 数组表示法$obj['section2']['row4']['key2'];

2) 点运算符$obj.section2.row4.key2;

Nb: 请使用数组表示法 如果密钥中有 space,则在未知密钥的情况下是安全的

如果你需要它遍历你可以在循环中使用的所有键