在 JavaScript 中使用 JSON 对象数组
JSON 对象是一个简单的 JavaScript 对象。我们可以创建一个包含许多类似 JSON 对象的数组。与 C、C++、Java 等语言不同,在 javascript 中,处理 JSON 对象数组很容易。它类似于 C 语言中的结构数组或 Java 中的类对象数组。在本文中,我们将讨论如何通过迭代并在其中查找元素来创建 JSON 对象数组。
创建 JSON 对象数组
我们可以通过将 JSON 数组分配给变量或使用 .push()
运算符在对象数组中动态添加值来创建 JSON 对象数组,或者使用循环结构在数组的索引处添加对象,例如 for
循环或 while
循环。参考以下代码更好理解。
var months = [{'id': 1, 'name': 'January'}, {'id': 2, 'name': 'February'}];
console.log(JSON.stringify(months));
var monthNames = ['January', 'February'];
var month = {};
var monthsArray = [];
for (let i = 0; i < 2; i++) {
month.id = (i + 1);
month.name = monthNames[i];
monthsArray.push({...month});
}
console.log(JSON.stringify(monthsArray));
输出:
[{"id":1,"name":"January"},{"id":2,"name":"February"}]
[{"id":1,"name":"January"},{"id":2,"name":"February"}]
在上面的代码中,months
变量保存显式分配的 JSON 对象数组,而 monthsArray
是通过在 for
循环内分配值创建的 JSON 对象数组。我们使用 .push()
数组函数将生成的 javascript 对象添加到 monthsArray
的末尾。请注意,当使用 JavaScript console.log()
语句记录时,这两个数组显示相同的结构。JSON.stringify()
函数将 JSON 数组转换为字符串格式,使其成为人类可读的格式。
从 JSON 对象数组访问对象
我们已经创建了一个 JSON 对象数组。让我们看看如何访问这个数组的元素。该方法与我们对简单字符串数组或数字数组所做的相同。我们可以使用数组索引(从 0
开始)访问数组对象,并在该索引处操作对象值。参考以下代码。
var months = [{'id': 1, 'name': 'January'}, {'id': 2, 'name': 'February'}];
console.log(months[0].id);
console.log(months[0].name);
months[0].id = 3;
months[0].name = 'March';
console.log(months[0].id);
console.log(months[0].name);
输出:
1
January
3
March
在代码中,我们通过使用 array Index
访问 months
数组的第一个索引来更改对象参数的值。类似地,我们可以使用其索引更改数组中任何其他对象的值。
迭代 JSON 对象数组
我们可以像处理字符串数组或数字数组一样迭代对象数组。我们可以使用 for 循环
或 while 循环
来达到我们的目的。我们可以使用数组索引访问元素。我们将数组从第 0 个索引迭代到数组长度。.length
属性也返回对象数组的长度。请参考以下代码,其中显示了迭代数组并打印其中每个对象的值。
var months = [{'id': 1, 'name': 'January'}, {'id': 2, 'name': 'February'}];
for (let i = 0; i < months.length; i++) {
console.log(`${i} id:${months[i].id}, name:${months[i].name}`)
}
输出:
0 id:1, name:January
1 id:2, name:February
将对象添加到 JSON 对象数组
我们创建了一个对象数组并迭代它们。现在让我们看看如何向 JSON 数组添加元素。我们可以使用 .push()
函数将一个 JSON 对象添加到数组的末尾。.unshift()
函数在 JSON 数组的开头添加一个元素。.splice()
在数组中的指定索引处插入一个对象。请参考以下描述这些函数用法的代码。
var months = [{'id': 1, 'name': 'January'}, {'id': 2, 'name': 'February'}];
months.push({'id': 4, 'name': 'April'});
console.log(JSON.stringify(months));
months.unshift({'id': 12, 'name': 'December'})
console.log(JSON.stringify(months));
months.splice(3, 0, {'id': 3, 'name': 'March'});
console.log(JSON.stringify(months));
输出:
[{"id":1,"name":"January"},{"id":2,"name":"February"},{"id":4,"name":"April"}]
[{"id":12,"name":"December"},{"id":1,"name":"January"},{"id":2,"name":"February"},{"id":4,"name":"April"}]
[{"id":12,"name":"December"},{"id":1,"name":"January"},{"id":2,"name":"February"},{"id":3,"name":"March"},{"id":4,"name":"April"}]
请注意,我们可以使用 .splice()
函数将数组中的对象替换为作为参数传递的新值。.splice()
方法的第一个参数是我们执行操作的索引。作为第二个参数,我们提到了我们希望替换的元素数量。最后一个参数是我们插入到数组中的值。
从 JSON 对象数组中删除对象
我们可以以类似于简单 JavaScript 数组的方式从对象数组中删除元素。我们可以使用 javascript 的 .pop()
方法从 JSON 对象数组的末尾删除元素。.shift()
从 JSON 对象数组的开头删除一个对象。.splice()
函数删除 JSON 数组指定索引处的元素。参考以下代码。
var months = [
{'id': 12, 'name': 'December'}, {'id': 1, 'name': 'January'},
{'id': 2, 'name': 'February'}, {'id': 3, 'name': 'March'},
{'id': 4, 'name': 'April'}
];
months.shift();
console.log(JSON.stringify(months));
months.pop();
console.log(JSON.stringify(months));
months.splice(1, 1);
console.log(JSON.stringify(months));
输出:
[{"id":1,"name":"January"},{"id":2,"name":"February"},{"id":3,"name":"March"},{"id":4,"name":"April"}]
[{"id":1,"name":"January"},{"id":2,"name":"February"},{"id":3,"name":"March"}]
[{"id":1,"name":"January"},{"id":3,"name":"March"}]
从 JSON 对象数组中搜索元素
我们可以使用 .indexOf()
或 includes()
来检查一个元素是否存在于一个简单的字符串数组中。但是这些方法不适用于对象数组。我们可以使用某些类似的函数,如 .filter()
、.find()
、findIndex()
来检查数组中是否存在元素。我们可以手动迭代数组并使用循环结构(如 for
、while
循环等)检查元素是否存在,但这可能是最后一个要考虑的选项,因为它会导致大量代码。javascript 内置函数如 .filter()
、.find()
、findIndex()
可用于在 JSON 对象数组中搜索对象。.filter()
函数返回一个包含满足特定条件的对象的数组,.find()
返回满足作为内联函数传递给它的条件的对象,.findIndex()
将返回如果可以在数组中找到对象的索引,则返回 -1
。因此,通过了解函数的返回类型,我们可以在 JSON 对象数组中设计搜索功能。参考以下代码可以更好地理解 .filter()
、.find()
、findIndex()
的用法。
var months = [
{'id': 12, 'name': 'December'}, {'id': 1, 'name': 'January'},
{'id': 2, 'name': 'February'}, {'id': 3, 'name': 'March'},
{'id': 4, 'name': 'April'}
];
(months.filter(i => i.name === 'April').length) ?
console.log('April month found') :
console.log('Not found');
(months.find(i => i.name === 'January') != {}) ?
console.log('January month found') :
console.log('Not found');
(months.findIndex(i => i.name === 'April') > -1) ?
console.log('April month found') :
console.log('Not found');
输出:
April month found
January month found
April month found
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。