suchen

Heim  >  Fragen und Antworten  >  Hauptteil

Wie greife ich auf verschachtelte Objekte, Arrays oder JSON zu und verarbeite sie?

Ich habe eine verschachtelte Datenstruktur, die Objekte und Arrays enthält. Wie kann ich Informationen extrahieren, also auf bestimmte oder mehrere Werte (oder Schlüssel) zugreifen?

Zum Beispiel:

var data = {
    code: 42,
    items: [{
        id: 1,
        name: 'foo'
    }, {
        id: 2,
        name: 'bar'
    }]
};

Wie greife ich zuitems中第二项的name?

P粉864872812P粉864872812497 Tage vor742

Antworte allen(2)Ich werde antworten

  • P粉476547076

    P粉4765470762023-10-10 16:45:24

    您可以通过这种方式访问​​它

    data.items[1].name

    data["items"][1]["name"]

    两种方式都是平等的。

    Antwort
    0
  • P粉002023326

    P粉0020233262023-10-10 13:48:33

    预备知识

    JavaScript 只有一种可以包含多个值的数据类型:对象数组是一种特殊形式的对象。

    (普通)对象具有以下形式

    {key: value, key: value, ...}

    数组的形式为

    [value, value, ...]

    数组和对象都公开一个key -> value 结构。数组中的键必须是数字,而任何字符串都可以用作对象中的键。键值对也称为“属性”

    可以使用点符号访问属性

    const value = obj.someProperty;

    括号表示法,如果属性名称不是有效的 JavaScript 标识符名称​​[spec],或者名称是变量的值:

    // the space is not a valid character in identifier names
    const value = obj["some Property"];
    
    // property name as variable
    const name = "some Property";
    const value = obj[name];

    因此,数组元素只能使用括号表示法访问:

    const value = arr[5]; // arr.5 would be a syntax error
    
    // property name / index as variable
    const x = 5;
    const value = arr[x];

    等等...JSON 怎么样?

    JSON 是数据的文本表示形式,就像 XML、YAML、CSV 等。要处理此类数据,首先必须将其转换为 JavaScript 数据类型,即数组和对象(刚刚解释了如何处理这些数据)。问题 在 JavaScript 中解析 JSON? 中解释了如何解析 JSON。< /p>

    进一步阅读材料

    如何访问数组和对象是 JavaScript 基础知识,因此建议阅读 MDN JavaScript 指南,尤其是各个部分



    访问嵌套数据结构

    嵌套数据结构是引用其他数组或对象的数组或对象,即它的值是数组或对象。可以通过连续应用点或括号表示法来访问此类结构。

    这是一个例子:

    const data = {
        code: 42,
        items: [{
            id: 1,
            name: 'foo'
        }, {
            id: 2,
            name: 'bar'
        }]
    };

    假设我们想要访问第二个项目的名称

    以下是我们如何逐步做到这一点:

    正如我们所见,data 是一个对象,因此我们可以使用点表示法访问其属性。 items 属性的访问方式如下:

    data.items

    该值是一个数组,要访问它的第二个元素,我们必须使用括号表示法:

    data.items[1]

    这个值是一个对象,我们再次使用点表示法来访问name属性。所以我们最终得到:

    const item_name = data.items[1].name;

    或者,我们可以对任何属性使用括号表示法,特别是如果名称包含使其对点表示法无效的字符:

    const item_name = data['items'][1]['name'];

    我正在尝试访问某个属性,但只得到 undefined 信息?

    大多数情况下,当您遇到未定义时,对象/数组根本不具有具有该名称的属性。

    const foo = {bar: {baz: 42}};
    console.log(foo.baz); // undefined

    使用console.logconsole.dir 和检查对象/数组的结构。您尝试访问的属性实际上可能是在嵌套对象/数组上定义的。

    console.log(foo.bar.baz); // 42

    如果属性名称是动态的并且我事先不知道它们怎么办?

    如果属性名称未知或者我们想要访问对象/数组元素的所有属性,我们可以使用 for...in [MDN] 循环对象和 for < em>[MDN] 循环数组以迭代所有属性/元素。

    对象

    要迭代data的所有属性,我们可以迭代对象,如下所示:

    for (const prop in data) {
        // `prop` contains the name of each property, i.e. `'code'` or `'items'`
        // consequently, `data[prop]` refers to the value of each property, i.e.
        // either `42` or the array
    }

    根据对象的来源(以及您想要执行的操作),您可能必须在每次迭代中测试该属性是否确实是对象的属性,还是继承的属性。您可以使用 Object#hasOwnProperty [MDN]

    作为 for...inhasOwnProperty 的替代方案,您可以使用 Object.keys [MDN] 获取属性名称数组

    Object.keys(data).forEach(function(prop) {
      // `prop` is the property name
      // `data[prop]` is the property value
    });

    数组

    要迭代 data.items 数组 的所有元素,我们使用 for 循环:

    for(let i = 0, l = data.items.length; i < l; i++) {
        // `i` will take on the values `0`, `1`, `2`,..., i.e. in each iteration
        // we can access the next element in the array with `data.items[i]`, example:
        // 
        // var obj = data.items[i];
        // 
        // Since each element is an object (in our example),
        // we can now access the objects properties with `obj.id` and `obj.name`. 
        // We could also use `data.items[i].id`.
    }

    也可以使用 for...in 来迭代数组,但有一些原因应该避免这种情况:为什么在 JavaScript 中使用数组的“for(var item in list)”被认为是不好的做法?.

    随着 ECMAScript 5 的浏览器支持不断增加,数组方法 forEach [MDN] 也成为一个有趣的替代方案:

    data.items.forEach(function(value, index, array) {
        // The callback is executed for each element in the array.
        // `value` is the element itself (equivalent to `array[index]`)
        // `index` will be the index of the element in the array
        // `array` is a reference to the array itself (i.e. `data.items` in this case)
    });

    在支持 ES2015 (ES6) 的环境中,您还可以使用 for...of [MDN] 循环,其中不仅适用于数组,还适用于任何可迭代对象

    for (const item of data.items) {
       // `item` is the array element, **not** the index
    }

    在每次迭代中,for...of 直接为我们提供可迭代的下一个元素,没有“索引”可供访问或使用。


    如果我不知道数据结构的“深度”怎么办?

    除了未知的键之外,数据结构的“深度”(即有多少个嵌套对象)也可能是未知的。如何访问深度嵌套的属性通常取决于确切的数据结构。

    但是如果数据结构包含重复模式,例如二叉树的表示形式,解决方案通常包括递归 < em>[维基百科]访问数据结构的每个级别。

    下面是获取二叉树的第一个叶节点的示例:

    function getLeaf(node) {
        if (node.leftChild) {
            return getLeaf(node.leftChild); // <- recursive call
        }
        else if (node.rightChild) {
            return getLeaf(node.rightChild); // <- recursive call
        }
        else { // node must be a leaf node
            return node;
        }
    }
    
    const first_leaf = getLeaf(root);

    const root = {
        leftChild: {
            leftChild: {
                leftChild: null,
                rightChild: null,
                data: 42
            },
            rightChild: {
                leftChild: null,
                rightChild: null,
                data: 5
            }
        },
        rightChild: {
            leftChild: {
                leftChild: null,
                rightChild: null,
                data: 6
            },
            rightChild: {
                leftChild: null,
                rightChild: null,
                data: 7
            }
        }
    };
    function getLeaf(node) {
        if (node.leftChild) {
            return getLeaf(node.leftChild);
        } else if (node.rightChild) {
            return getLeaf(node.rightChild);
        } else { // node must be a leaf node
            return node;
        }
    }
    
    console.log(getLeaf(root).data);

    Antwort
    0
  • StornierenAntwort