如何访问和处理嵌套对象、数组或json?

rkue9o1l  于 2021-09-08  发布在  Java
关注(0)|答案(5)|浏览(332)

我有一个包含对象和数组的嵌套数据结构。如何提取信息,即访问特定或多个值(或键)?
例如:

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

我怎样才能进入这个网站 name 第二项 items ?

ekqde3dh

ekqde3dh1#

预备赛

javascript只有一种数据类型可以包含多个值:object。数组是对象的一种特殊形式。
(普通)对象具有以下形式:

{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数据类型,即数组和对象(刚才已经解释了如何处理这些数据)。如何解析json在javascript中解析json的问题中进行了解释。

进一步阅读材料

如何访问数组和对象是基本的javascript知识,因此建议阅读mdn javascript指南,尤其是以下章节
处理对象
阵列
有说服力的javascript数据结构

访问嵌套数据结构

嵌套数据结构是指引用其他数组或对象的数组或对象,即其值是数组或对象。这种结构可以通过连续应用点或括号符号来访问。
以下是一个例子:

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

假设我们想要访问 name 第二项。
以下是我们如何一步一步地做到这一点:
我们可以看到 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 [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...in 具有 hasOwnProperty ,你可以使用 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项)”?。
随着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]循环,它不仅适用于阵列,而且适用于任何iterable:

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

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

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

除了未知键之外,数据结构的“深度”(即有多少嵌套对象)也可能未知。如何访问深度嵌套的属性通常取决于确切的数据结构。
但是,如果数据结构包含重复模式,例如二叉树的表示,则解决方案通常包括递归地访问数据结构的每一级。
下面是获取二叉树的第一个叶节点的示例:

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

访问具有未知键和深度的嵌套数据结构的更通用的方法是测试值的类型并相应地采取行动。
下面是一个将嵌套数据结构中的所有基元值添加到数组中的示例(假设它不包含任何函数)。如果遇到对象(或数组),我们只需调用 toArray 再次使用该值(递归调用)。

function toArray(obj) {
    const result = [];
    for (const prop in obj) {
        const value = obj[prop];
        if (typeof value === 'object') {
            result.push(toArray(value)); // <- recursive call
        }
        else {
            result.push(value);
        }
    }
    return result;
}
const data = {
  code: 42,
  items: [{
    id: 1,
    name: 'foo'
  }, {
    id: 2,
    name: 'bar'
  }]
};

function toArray(obj) {
  const result = [];
  for (const prop in obj) {
    const value = obj[prop];
    if (typeof value === 'object') {
      result.push(toArray(value));
    } else {
      result.push(value);
    }
  }
  return result;
}

console.log(toArray(data));

助手

由于复杂对象或数组的结构不一定明显,因此我们可以在每一步检查值以决定如何进一步移动。 console.log [mdn]和 console.dir [mdn]请帮助我们这样做。例如(chrome控制台的输出):

> console.log(data.items)
 [ Object, Object ]

在这里我们看到 data.items 是一个包含两个元素的数组,这两个元素都是对象。在chrome控制台中,甚至可以立即展开和检查对象。

> console.log(data.items[1])
  Object
     id: 2
     name: "bar"
     __proto__: Object

这告诉我们 data.items[1] 是一个对象,展开后我们看到它有三个属性, id , name__proto__ . 后者是用于对象的原型链的内部属性。然而,原型链和继承超出了这个答案的范围。

elcex8rz

elcex8rz2#

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

data.items[1].name

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

两种方法都是平等的。

u1ehiz5o

u1ehiz5o3#

对象和数组有许多内置方法,可以帮助您处理数据。
注意:在许多示例中,我使用的是箭头函数。它们类似于函数表达式,但它们绑定了 this 从词汇上评价。

object.keys()、object.values()(es 2017)和object.entries()(es 2017) Object.keys() 返回对象键的数组, Object.values() 返回对象值的数组,并 Object.entries() 以格式返回对象键和相应值的数组 [key, value] .

const obj = {
  a: 1
 ,b: 2
 ,c: 3
}

console.log(Object.keys(obj)) // ['a', 'b', 'c']
console.log(Object.values(obj)) // [1, 2, 3]
console.log(Object.entries(obj)) // [['a', 1], ['b', 2], ['c', 3]]

object.entries(),具有for of循环和解构赋值

const obj = {
  a: 1
 ,b: 2
 ,c: 3
}

for (const [key, value] of Object.entries(obj)) {
  console.log(`key: ${key}, value: ${value}`)
}

迭代计算结果非常方便 Object.entries() 使用for循环和解构赋值。
for of循环允许您迭代数组元素。语法是 for (const element of array) (我们可以替换 const 具有 varlet ,但最好使用 const 如果我们不打算修改 element ).
通过分解结构分配,可以从数组或对象中提取值并将其分配给变量。在这种情况下 const [key, value] 意味着不是分配 [key, value] 排列到 element ,我们将该数组的第一个元素分配给 key 第二个元素是 value . 这相当于:

for (const element of Object.entries(obj)) {
  const key = element[0]
       ,value = element[1]
}

正如您所看到的,分解使这变得简单得多。

array.prototype.every()和array.prototype.some()

这个 every() 方法返回 true 如果指定的回调函数返回 true 对于数组的每个元素。这个 some() 方法返回 true 如果指定的回调函数返回 true 对于某些(至少一个)元素。

const arr = [1, 2, 3]

// true, because every element is greater than 0
console.log(arr.every(x => x > 0))
// false, because 3^2 is greater than 5
console.log(arr.every(x => Math.pow(x, 2) < 5))
// true, because 2 is even (the remainder from dividing by 2 is 0)
console.log(arr.some(x => x % 2 === 0))
// false, because none of the elements is equal to 5
console.log(arr.some(x => x === 5))

array.prototype.find()和array.prototype.filter()

这个 find() 方法返回满足所提供回调函数的第一个元素。这个 filter() 方法返回满足所提供回调函数的所有元素的数组。

const arr = [1, 2, 3]

// 2, because 2^2 !== 2
console.log(arr.find(x => x !== Math.pow(x, 2)))
// 1, because it's the first element
console.log(arr.find(x => true))
// undefined, because none of the elements equals 7
console.log(arr.find(x => x === 7))

// [2, 3], because these elements are greater than 1
console.log(arr.filter(x => x > 1))
// [1, 2, 3], because the function returns true for all elements
console.log(arr.filter(x => true))
// [], because none of the elements equals neither 6 nor 7
console.log(arr.filter(x => x === 6 || x === 7))

array.prototype.map()

这个 map() 方法返回一个数组,其中包含对数组元素调用提供的回调函数的结果。

const arr = [1, 2, 3]

console.log(arr.map(x => x + 1)) // [2, 3, 4]
console.log(arr.map(x => String.fromCharCode(96 + x))) // ['a', 'b', 'c']
console.log(arr.map(x => x)) // [1, 2, 3] (no-op)
console.log(arr.map(x => Math.pow(x, 2))) // [1, 4, 9]
console.log(arr.map(String)) // ['1', '2', '3']

array.prototype.reduce()

这个 reduce() 方法通过使用两个元素调用提供的回调函数,将数组缩减为单个值。

const arr = [1, 2, 3]

// Sum of array elements.
console.log(arr.reduce((a, b) => a + b)) // 6
// The largest number in the array.
console.log(arr.reduce((a, b) => a > b ? a : b)) // 3

这个 reduce() 方法接受可选的第二个参数,即初始值。当调用的数组 reduce() can有零个或一个元素。例如,如果我们想创建一个函数 sum() 它将数组作为参数并返回所有元素的和,我们可以这样写:

const sum = arr => arr.reduce((a, b) => a + b, 0)

console.log(sum([]))     // 0
console.log(sum([4]))    // 4
console.log(sum([2, 5])) // 7
ukxgm1gy

ukxgm1gy4#

以防您试图访问 item 从示例结构 idname ,在不知道它在数组中的位置的情况下,最简单的方法是使用下划线.js库:

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

_.find(data.items, function(item) {
  return item.id === 2;
});
// Object {id: 2, name: "bar"}

根据我的经验,使用高阶函数代替 forfor..in 循环产生的代码更易于推理,因此更易于维护。
只要我的2美分。

i34xakig

i34xakig5#

有时,使用字符串访问嵌套对象是可取的。例如,简单方法是第一级

var obj = { hello: "world" };
var key = "hello";
alert(obj[key]);//world

但复杂的json通常不是这样。随着json变得越来越复杂,在json中查找值的方法也变得复杂。导航json的递归方法是最好的,如何利用递归将取决于搜索的数据类型。如果涉及到条件语句,json搜索是一个很好的工具。
如果正在访问的属性已经已知,但路径很复杂,例如在该对象中

var obj = {
 arr: [
    { id: 1, name: "larry" },    
    { id: 2, name: "curly" },
    { id: 3, name: "moe" }
 ]
};

你知道你想得到对象中数组的第一个结果,也许是

相关问题