gpt4 book ai didi

javascript - 无法从数组过滤器返回正确的值

转载 作者:行者123 更新时间:2023-12-01 01:06:05 24 4
gpt4 key购买 nike

我试图从这个对象数据数组中返回对象,其中嵌套对象中的 checked 为 true。在回调函数内部,它仅返回 checked 为 true

的对象
{name: "Beginner", skills: Array(1)}
{name: "Intermediate", skills: Array(1)}
{name: "Professional", skills: Array(0)}

但是当我返回并记录它时,它显示了两个对象的数组

{name: "Beginner", skills: Array(2)}
{name: "Intermediate", skills: Array(2)}
{name: "Professional", skills: Array(2)}

我无法弄清楚我在哪里犯了错误

const data = [{
"name": "Beginner",
"skills": [{
"name": "Skill 1",
"checked": false
},
{
"name": "Skill 2",
"checked": true
}
]
},
{
"name": "Intermediate",
"skills": [{
"name": "Skill 1",
"checked": true
},
{
"name": "Skill 2",
"checked": false
}
]
},
{
"name": "Professional",
"skills": [{
"name": "Skill 1",
"checked": false
},
{
"name": "Skill 2",
"checked": false
}
]
},
];


let newData = data.filter(function(item) {
let dt = {
name: item.name,
skills: item.skills.filter(elem => elem.checked)
}
console.log(dt)
return dt
});
console.log(newData)

最佳答案

尝试使用 map 而不是过滤器

const data = [{
"name": "Beginner",
"skills": [{
"name": "Skill 1",
"checked": false
},
{
"name": "Skill 2",
"checked": true
}
]
},
{
"name": "Intermediate",
"skills": [{
"name": "Skill 1",
"checked": true
},
{
"name": "Skill 2",
"checked": false
}
]
},
{
"name": "Professional",
"skills": [{
"name": "Skill 1",
"checked": false
},
{
"name": "Skill 2",
"checked": false
}
]
},
];


let newData = data.map(item => {
return {
name: item.name,
skills: item.skills.filter(elem => elem.checked)
}
});
console.log(newData)

关于javascript - 无法从数组过滤器返回正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55626685/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com