[英]Create a new array of boolean values by comparing two arrays with objects
I have a question about creating JavaScript arrays.我有一个关于创建 JavaScript 数组的问题。 Here's what I want to do.这就是我想做的。
I have two arrays .我有两个数组。 Each array has object(s) in them.每个数组中都有对象。
The first array has exactly 5 objects, each with a key/value pair (id/name).第一个数组正好有 5 个对象,每个对象都有一个键/值对(id/name)。 This array will ALWAYS have 5 objects.这个数组总是有 5 个对象。
Here's what it looks like...这是它的样子......
[
{
"id": 1,
"name": "AnalyticalAdmin"
},
{
"id": 2,
"name": "Analyst"
},
{
"id": 4,
"name": "AdminReviewer"
},
{
"id": 5,
"name": "SystemAdministrator"
},
{
"id": 6,
"name": "CaseworkSTRTechLeader"
}
]
The second array will have either ...第二个数组将具有...
no objects,没有对象,
4 or less objects, 4个或更少的物体,
exactly 5 objects.正好 5 个对象。
In the example below, the second array only has one of the 5 objects in the first array...在下面的示例中,第二个数组只有第一个数组中的 5 个对象中的一个...
[
{
"id": 4,
"name": "AdminReviewer"
}
]
I need to create a third array that has exactly 5 boolean values that are determined by comparing the first two arrays.我需要创建第三个数组,其中正好有 5 个布尔值,这些值是通过比较前两个数组来确定的。
For example, based on the first two arrays above, the third array would be...例如,基于上面的前两个数组,第三个数组将是......
[false, false, true, false, false]
The reason the third array would look like this is because "AdminReviewer" is the third object in the first array, so the third boolean value in the third array would be true (since it's a match).第三个数组看起来像这样的原因是因为“AdminReviewer”是第一个数组中的第三个对象,所以第三个数组中的第三个布尔值将为真(因为它是匹配的)。
But because the first, second, fourth, and fifth objects in the first array do not exist in the second array, their boolean equivalent in the third array would be false.但是因为第一个数组中的第一个、第二个、第四个和第五个对象在第二个数组中不存在,所以它们在第三个数组中的布尔等效项将是错误的。
To accomplish this, I know I need to either do a compare function on the first two arrays to create the third array (of booleans) or I need to run a for loop on the first array, comparing it to the second array to create the third array (of booleans).为此,我知道我需要对前两个数组执行比较函数以创建第三个数组(布尔值),或者我需要在第一个数组上运行for 循环,将其与第二个数组进行比较以创建第三个数组(布尔值)。
Can anyone help me with this?谁能帮我这个?
This could be done as follows:这可以按如下方式完成:
const filterStrings = filterArray.map(o => JSON.stringify(o));
const result = baseArray.map(o => filterStrings.includes(JSON.stringify(o)));
Please take a look at below runnable code and see how it works.请看下面的可运行代码,看看它是如何工作的。
const baseArray = [ { "id": 1, "name": "AnalyticalAdmin" }, { "id": 2, "name": "Analyst" }, { "id": 4, "name": "AdminReviewer" }, { "id": 5, "name": "SystemAdministrator" }, { "id": 6, "name": "CaseworkSTRTechLeader" } ]; const filterArray = [ { "id": 4, "name": "AdminReviewer" } ]; const filterStrings = filterArray.map(o => JSON.stringify(o)); const result = baseArray.map(o => filterStrings.includes(JSON.stringify(o))); console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.