javascript – 根据条件检查迭代每个对象数组
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 根据条件检查迭代每个对象数组,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1758字,纯文字阅读大概需要3分钟。
内容图文
![javascript – 根据条件检查迭代每个对象数组](/upload/InfoBanner/zyjiaocheng/729/bc9f0c2517f34f9e97c210f8571e3829.jpg)
我有一个场景是我需要迭代对象中的每个父/子数组.
每个祖父母可以有多个父母,以同样的方式,每个父母可以有多个孩子,每个孩子可以有多个子孩子等等.
我需要在迭代时检查类型是“父”还是“子”,然后将name属性推送到预期输出中提到的数组.
输入对象:
var inputObject = {
"id": 1,
"name": "Grand Parent 1",
"type": "GrandParent",
"childType": [
{
"id": 2,
"type": "Parent",
"childType": [
{
"id": 3,
"type": "Child",
"childType": [],
"name": "Child 11"
},
{
"id": 4,
"type": "Child",
"childType": [],
"name": "Child 12"
}
],
"name": "Parent 1"
},
{
"id": 5,
"type": "Parent",
"childType": [
{
"id": 6,
"type": "Child",
"childType": [],
"name": "Child 21"
}
],
"name": "Parent 2"
},
{
"id": 7,
"type": "Parent",
"childType": [
{
"id": 8,
"type": "Child",
"childType": [],
"name": "Child 31"
}
],
"name": "Parent 3"
}
]
}
代码尝试:
function handleData({childType, ...rest}){
const res = [];
res.push(rest.name);
if(childType){
if(rest.type == "Child")
res.push(...handleData(childType));
}
return res;
}
const res = handleData(inputObject);
预期产出:
If type selected is "Parent"
["Parent 1", "Parent 2, Parent 3"]
if type selected is "Child"
["Child 11", "Child 12", "Child 21", "Child 31"]
解决方法:
你可以做一个使用flatMap()的递归函数:
const obj = {id:1,name:"Grand Parent 1",type:"GrandParent",childType:[{id:2,type:"Parent",childType:[{id:3,type:"Child",childType:[],name:"Child 11"},{id:4,type:"Child",childType:[],name:"Child 12"}],name:"Parent 1"},{id:5,type:"Parent",childType:[{id:6,type:"Child",childType:[],name:"Child 21"}],name:"Parent 2"},{id:7,type:"Parent",childType:[{id:8,type:"Child",childType:[],name:"Child 31"}],name:"Parent 3"}]};
const get = (o, t) => o.type === t ? [o.name] : o.childType.flatMap(c => get(c, t));
console.log(get(obj, 'GrandParent'));
console.log(get(obj, 'Parent'));
console.log(get(obj, 'Child'));
内容总结
以上是互联网集市为您收集整理的javascript – 根据条件检查迭代每个对象数组全部内容,希望文章能够帮你解决javascript – 根据条件检查迭代每个对象数组所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。