我正在尝试从此对象的数据数组中返回对象,其中checked
在嵌套对象中为true。在回调函数内部,它仅返回checked
为真的那些对象
{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)
答案 0 :(得分: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.map(item => {
return {
name: item.name,
skills: item.skills.filter(elem => elem.checked)
}
});
console.log(newData)
答案 1 :(得分:0)
使用reduce()
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.reduce((acc, item) => [...acc, {
name: item.name,
skills: item.skills.filter(elem => elem.checked)
}], []);
console.log(newData)
答案 2 :(得分:0)
您不过滤数组,因为您总是返回真实值,这不是结果,而是用于获取此项的标志。
要进行过滤,您需要稍后获取嵌套数组的长度。
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 }] }],
newData = data
.map(({ name, skills}) => ({ name, skills: skills.filter(({ checked }) => checked) }))
.filter(({ skills: { length } }) => length)
console.log(newData)
.as-console-wrapper { max-height: 100% !important; top: 0; }