On average I work with JSON data 18 times a week. And I still need to google for specific ways to manipulate them almost every time. What if there was an ultimate guide that could always give you the answer?
平均而言,我每周处理JSON数据18次。 而且我仍然需要Google搜索几乎每次都可以使用的特定方法。 如果有最终指南可以始终为您提供答案怎么办?
In this article, I'll show you the basics of working with object arrays in JavaScript.
在本文中,我将向您展示在JavaScript中使用对象数组的基础知识。
If you ever worked with a JSON structure, you've worked with JavaScript objects. Quite literally. JSON stands for JavaScript Object Notation.
如果您曾经使用过JSON结构,那么您就已经使用过JavaScript对象。 毫不夸张的说。 JSON代表JavaScript对象符号。
Creating an object is as simple as this:
创建对象是如此简单:
{
"color": "purple",
"type": "minivan",
"registration": new Date('2012-02-03'),
"capacity": 7
}
This object represents a car. There can be many types and colors of cars, each object then represents a specific car.
该对象代表一辆汽车。 汽车可以有多种类型和颜色,每个对象代表一个特定的汽车。
Now, most of the time you get data like this from an external service. But sometimes you need to create objects and their arrays manually. Like I did when I was creating this e-shop:
现在,大多数时候您都是从外部服务获取此类数据。 但是有时您需要手动创建对象及其数组。 就像我创建此电子商店时一样:
Considering each category list item looks like this in HTML:
考虑每个类别列表项在HTML中看起来像这样:
I didn't want to have this code repeated 12 times, which would make it unmaintainable.
我不想将此代码重复12次,这将使其无法维护。
But let's get back to cars. Let's take a look at this set of cars:
但是,让我们回到汽车上。 让我们看一下这组汽车:
We can represent it as an array this way:
我们可以这样将它表示为一个数组:
let cars = [
{
"color": "purple",
"type": "minivan",
"registration": new Date('2017-01-03'),
"capacity": 7
},
{
"color": "red",
"type": "station wagon",
"registration": new Date('2018-03-03'),
"capacity": 5
},
{
...
},
...
]
Arrays of objects don't stay the same all the time. We almost always need to manipulate them. So let's take a look at how we can add objects to an already existing array.
对象数组并非始终保持不变。 我们几乎总是需要操纵它们。 因此,让我们看一下如何将对象添加到现有数组中。
To add an object at the first position, use Array.unshift
.
要在第一个位置添加对象,请使用Array.unshift
。
let car = {
"color": "red",
"type": "cabrio",
"registration": new Date('2016-05-02'),
"capacity": 2
}
cars.unshift(car);
To add an object at the last position, use Array.push
.
要在最后一个位置添加对象,请使用Array.push
。
let car = {
"color": "red",
"type": "cabrio",
"registration": new Date('2016-05-02'),
"capacity": 2
}
cars.push(car);
To add an object in the middle, use Array.splice
. This function is very handy as it can also remove items. Watch out for its parameters:
要在中间添加一个对象,请使用Array.splice
。 此功能非常方便,因为它也可以删除项目。 注意其参数:
Array.splice(
{index where to start},
{how many items to remove},
{items to add}
);
So if we want to add the red Volkswagen Cabrio on the fifth position, we'd use:
因此,如果我们要在第五个位置添加红色大众敞篷车,我们将使用:
let car = {
"color": "red",
"type": "cabrio",
"registration": new Date('2016-05-02'),
"capacity": 2
}
cars.splice(4, 0, car);
Let me ask you a question here: Why do you want to loop through an array of objects? The reason I'm asking is that the looping is almost never the primary cause of what we want to achieve.
让我在这里问您一个问题:为什么要遍历对象数组? 我要问的原因是循环几乎从来不是我们要实现的目标的主要原因。
JavaScript provides many functions that can solve your problem without actually implementing the logic in a general cycle. Let's take a look.
JavaScript提供了许多功能,可以解决您的问题,而无需在一般周期中实际实现逻辑。 让我们来看看。
Let's say we want to find a car that is red. We can use the function Array.find
.
假设我们想找到一辆红色的汽车。 我们可以使用Array.find
函数。
let car = cars.find(car => car.color === "red");
This function returns the first matching element:
此函数返回第一个匹配的元素:
console.log(car);
// output:
// {
// color: 'red',
// type: 'station wagon',
// registration: 'Sat Mar 03 2018 01:00:00 GMT+0100 (GMT+01:00)',
// capacity: 5
// }
It's also possible to search for multiple values:
也可以搜索多个值:
let car = cars.find(car => car.color === "red" && car.type === "cabrio");
let car = cars.find(car => car.color === "red" && car.type === "cabrio");
In that case we'll get the last car in the list.
在这种情况下,我们将获得列表中的最后一辆车。
The Array.find
function returns only one object. If we want to get all red cars, we need to use Array.filter
.
Array.find
函数仅返回一个对象。 如果要获得所有红色汽车,则需要使用Array.filter
。
let redCars = cars.filter(car => car.color === "red");
console.log(redCars);
// output:
// [
// {
// color: 'red',
// type: 'station wagon',
// registration: 'Sat Mar 03 2018 01:00:00 GMT+0100 (GMT+01:00)',
// capacity: 5
// },
// {
// color: 'red',
// type: 'cabrio',
// registration: 'Sat Mar 03 2012 01:00:00 GMT+0100 (GMT+01:00)',
// capacity: 2
// }
// ]
This is something we need very often. Transform an array of objects into an array of different objects. That's a job for Array.map
. Let's say we want to classify our cars into three groups based on their size.
这是我们经常需要的东西。 将对象数组转换为不同对象的数组。 这是Array.map
的工作。 假设我们要根据汽车的大小将其分为三类。
let sizes = cars.map(car => {
if (car.capacity <= 3){
return "small";
}
if (car.capacity <= 5){
return "medium";
}
return "large";
});
console.log(sizes);
// output:
// ['large','medium','medium', ..., 'small']
It's also possible to create a new object if we need more values:
如果我们需要更多的值,也可以创建一个新的对象:
let carsProperties = cars.map(car => {
let properties = {
"capacity": car.capacity,
"size": "large"
};
if (car.capacity <= 5){
properties['size'] = "medium";
}
if (car.capacity <= 3){
properties['size'] = "small";
}
return properties;
});
console.log(carsProperties);
// output:
// [
// { capacity: 7, size: 'large' },
// { capacity: 5, size: 'medium' },
// { capacity: 5, size: 'medium' },
// { capacity: 2, size: 'small' },
// ...
// ]
But what if we want the car object too? In that case we can enhance the object for a new property size
. This is a good use-case for the Array.forEach
function.
但是,如果我们也想要汽车对象怎么办? 在这种情况下,我们可以增强对象以获得新的属性size
。 这是Array.forEach
函数的一个很好的用例。
cars.forEach(car => {
car['size'] = "large";
if (car.capacity <= 5){
car['size'] = "medium";
}
if (car.capacity <= 3){
car['size'] = "small";
}
});
When we're done with transforming the objects, we usually need to sort them one way or another.
完成对象转换后,通常需要以一种或另一种方式对它们进行排序。
Typically, the sorting is based on a value of a property every object has. We can use the Array.sort
function, but we need to provide a function that defines the sorting mechanism.
通常,排序基于每个对象都具有的属性的值。 我们可以使用Array.sort
函数,但是我们需要提供一个定义排序机制的函数。
Let's say we want to sort the cars based on their capacity in descending order.
假设我们要根据汽车的降序对汽车进行排序。
let sortedCars = cars.sort((c1, c2) => (c1.capacity < c2.capacity) ? 1 : (c1.capacity > c2.capacity) ? -1 : 0);
console.log(sortedCars);
// output:
// [
// {
// color: 'purple',
// type: 'minivan',
// registration: 'Wed Feb 01 2017 00:00:00 GMT+0100 (GMT+01:00)',
// capacity: 7
// },
// {
// color: 'red',
// type: 'station wagon',
// registration: 'Sat Mar 03 2018 01:00:00 GMT+0100 (GMT+01:00)',
// capacity: 5
// },
// ...
// ]
The Array.sort
compares two objects and puts the first object in the second place if the result of the sorting function is positive. So you can look at the sorting function as if it was a question: Should the first object be placed in second place?
Array.sort
比较两个对象,如果排序函数的结果为正,则将第一个对象放在第二位。 因此,您可以看一下排序功能,就好像是一个问题:应该将第一个对象放在第二位吗?
Make sure to always add the case for zero when the compared value of both objects is the same to avoid unnecessary swaps.
当两个对象的比较值相同时,请确保始终将大小写加为零,以避免不必要的交换。
Array.every
and Array.some
come handy when we just need to check each object for a specific condition.
当我们只需要检查每个对象的特定条件时, Array.every
和Array.some
就派上用场了。
Do we have a red cabrio in the list of cars? Are all cars capable of transporting at least 4 people? Or more web-centric: Is there a specific product in the shopping cart?
汽车列表中有红色敞篷车吗? 所有的汽车都能载至少4人吗? 或更以网络为中心:购物车中是否有特定产品?
cars.some(car => car.color === "red" && car.type === "cabrio");
// output: true
cars.every(car => car.capacity >= 4);
// output: false
You may remember the function Array.includes
which is similar to Array.some
, but works only for primitive types.
您可能还记得Array.includes
函数,它类似于Array.some
,但仅适用于原始类型。
In this article, we went through the basic functions that help you create, manipulate, transform, and loop through arrays of objects. They should cover most cases you will stumble upon.
在本文中,我们介绍了一些基本功能,这些功能可以帮助您创建,操作,转换和循环对象数组。 它们应涵盖您偶然发现的大多数情况。
If you have a use-case that requires more advanced functionality, take a look at this detailed guide to arrays or visit the W3 schools reference.
如果您有一个需要更高级功能的用例,请查看此数组的详细指南,或访问W3学校参考 。
Or get in touch with me and I will prepare another article :-)
或者与我联系 ,我将准备另一篇文章:-)
翻译自: https://www.freecodecamp.org/news/javascript-array-of-objects-tutorial-how-to-create-update-and-loop-through-objects-using-js-array-methods/