如何解决访问嵌套对象数组的所有单个值?
我正在尝试访问每个项目的每个列表对象的单独计数值,以在数组中使用它们。我尝试了各种地图方法,但始终返回未定义状态。我需要一种动态的方法来收集这些计数,以便在添加更多列表,项目,位置和计数时,它会更新。
数据:
const data = [
{
name: "List1",items: [
{
name: "Item1",locations: [
{ position: "a",count: 20 },{ position: "b",count: 30 },],},{
name: "Item2",locations: [
{ position: "c",count: 40 },{ position: "d",count: 50 },{
name: "List2",items: [
{
name: "Item3",locations: [
{ position: "e",count: 60 },{ position: "f",count: 70 },{
name: "Item4",locations: [
{ position: "g",count: 80 },{ position: "h",count: 90 },];
所需结果:
const onlyCounts = [20,30,40,50,60,70,80,90];
任何提示或信息将不胜感激,谢谢!
解决方法
如果由于不确定嵌套对象的形状/键/深度而需要通用解决方案,那么只要您的数据没有任何周期,这是一种递归解决方案。
const getCounts = (value) =>
value.flatMap((el) =>
Object.entries(el).flatMap(([key,value]) => {
if (key === "count") return [value];
if (Array.isArray(value)) return getCounts(value);
return [];
})
);
const data = [
{
name: "List1",items: [
{
name: "Item1",locations: [
{ position: "a",count: 20 },{ position: "b",count: 30 }
]
},{
name: "Item2",locations: [
{ position: "c",count: 40 },{ position: "d",count: 50 }
]
}
]
},{
name: "List2",items: [
{
name: "Item3",locations: [
{ position: "e",count: 60 },{ position: "f",count: 70 }
]
},{
name: "Item4",locations: [
{ position: "g",count: 80 },{ position: "h",count: 90 }
]
}
]
}
];
const getCounts = (value) =>
value.flatMap((el) =>
Object.entries(el).flatMap(([key,value]) => {
if (key === "count") return [value];
if (Array.isArray(value)) return getCounts(value);
return [];
})
);
console.log(getCounts(data))
真正广义的解决方案
const getFieldArray = (value,field) =>
value.flatMap((el) =>
Object.entries(el).flatMap(([key,value]) => {
if (key === field) return [value];
if (Array.isArray(value)) return getFieldArray(value,field);
return [];
})
);
console.log(getFieldArray(data,'count'));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。