javascript - Node JS比较2个嵌套数组数据
问题描述
我非常喜欢与 block_idnew
进行Node JS
比较。following arrays
如果arrayB
block_id 与 block_id 匹配,arrayA
则添加新属性 isExist:true else false
var arrayB = [{ "block_id": 1 },{ "block_id": 3 }];
const arrayA = [
{
"block_id": 1,
"block_name": "test 1",
"children": [
{
"block_id": 2,
"block_name": "test 2",
"children": [
{
"block_id": 3,
"block_name": "test 2",
}
]
}
],
}
]
尝试以下代码进行比较
const result = arrayA.map(itemA => {
return arrayB
.filter(itemB => itemB.block_id === itemA.block_id)
.reduce((combo, item) => ({...combo, ...item}), {isExist: true})
});
我越来越关注
输出
[ { isExist: true, block_id: 1 } ]
预期的
[
{
"block_id": 1,
"block_name": "test 1",
"isExist": true,
"children": [
{
"block_id": 2,
"block_name": "test 2",
"isExist": false,
"children": [
{
"block_id": 3,
"block_name": "test 2",
"isExist": true,
}
]
}
],
}
];
解决方案
此函数是一个递归函数,因此您也可以循环遍历子项。
function procesArray(arr, arrayB) {
return arr.reduce((result, item) => {
const itemInB = arrayB.find(itemB => itemB.block_id == item.block_id)
if (itemInB)
item.isExist = true;
if (item.children)
procesArray(item.children, arrayB);
return [...result, item];
}, [])
}
现在,您可以像这样调用函数
const result = procesArray(arrayA, arrayB);
result
如下
[{
"block_id": 1,
"block_name": "test 1",
"children": [{
"block_id": 2,
"block_name": "test 2",
"children": [{
"block_id": 3,
"block_name": "test 2",
"isExist": true
}]
}],
"isExist": true
}]
推荐阅读
- php - 如何通过设置的日期和时间自动将电子邮件发送到 PHP 中的多个用户电子邮件
- python - matplotlib:在图形之外添加注释
- ios - Xcode 11 - 没有 iOS 13.1.2 模拟器(只有 13.0)
- arrays - 基于具有组 ID 的向量创建指标矩阵
- request - 有没有办法在 Spring Boot 中将媒体文件作为请求的一部分发送?
- azure - 将 Azure 资源从一个资源组移动到另一个资源组
- c# - 如何确定字符串是否包含此 SpriteFont 无法解析的字符?
- python - 两个具有相同键的 Python 字典:如何检测值不匹配的键?
- javascript - 在组件中返回 null 是否会阻止子组件呈现?
- node.js - 弹性搜索中如何根据 createdDate 等字段进行搜索