如何根据指定属性筛选JavaScript对象中的子对象?
筛选JavaScript对象中master属性为1的子对象
你提供的原对象存在语法错误,先修正为合法的JavaScript代码:
const USER = { LANGUAGE: { 'editable': 1, 'decimal': 0, 'degree': 0, 'master': 1, 0: ['', '', 0], 1: ['', '', 1], }, LUM: { 'editable': 1, 'decimal': 0, 'degree': 0, 'master': 0, 0: ['', '', 0], 1: ['', '', 1], 2: ['', '', 2], }, SP: { 'editable': 1, 'decimal': 0, 'degree': 0, 'master': 1, 0: ['', '', 0], 1: ['', '', 1], 2: ['', '', 2], }, };
方法一:使用Object.entries()和reduce()
这是现代JavaScript中简洁的写法,通过遍历对象键值对,筛选符合条件的子对象并构建新对象:
const filteredUser = Object.entries(USER).reduce((acc, [key, value]) => { if (value.master === 1) { acc[key] = value; } return acc; }, {}); console.log(filteredUser); // 输出结果:{ LANGUAGE: {...}, SP: {...} }
方法二:使用for...in循环
如果更倾向于直观的遍历写法,可以用for...in循环逐个检查子对象:
const filteredUser = {}; for (const key in USER) { if (USER[key].master === 1) { filteredUser[key] = USER[key]; } } console.log(filteredUser); // 输出结果同样包含LANGUAGE和SP两个子对象
两种方法都能得到仅包含master属性为1的子对象的新对象,且不会修改原USER对象。
内容的提问来源于stack exchange,提问作者Petitemo
相关产品推荐
相关产品推荐

