在对象中搜索指定值并将符合条件的对象存入新数组
需求说明
需要从给定的JSON对象集合中,筛选出包含指定字段的完整对象,并存入新数组。例如:当搜索字段为Continuous时,Doormerica和Hager这两个对象包含该字段,需将它们完整存入新数组。
原始数据集
{ "Doormerica": { "Floor Stops": [], "Overhead Stop": [], "Pull": [], "Chain Stop": [], "Continuous": [ "ALX", "AL", "QR" ], "Kick": [], "Back to Back Pull": [], "Concealed": [], "Butt": [], "Surface Mount": [], "Mop": [], "Armor": [], "Push": [], "Wall Stops": [] }, "Schlage": { "Mortise": [], "Cylindrical": [ "ALX", "AL", "QR" ], "Deadbolt": [], "Dummy": [], "Interconnected": [], "Cylinders": [] }, "Pemko": { "Sweeps": [ "345AV" ], "Permiter Seal": [ "303AS" ], "Thresholds": [ "170A" ], "Rain Drip": [ "346C" ], "Astragal": [] }, "LCN": { "Surface Mount": [ "4040XP" ], "Concealed": [] }, "Hager": { "Butt": [], "Continuous": [] } }
实现方案(JavaScript)
下面是实现该筛选逻辑的代码示例,可根据需求调整结果存储形式:
// 原始数据 const brandData = { "Doormerica": { "Floor Stops": [], "Overhead Stop": [], "Pull": [], "Chain Stop": [], "Continuous": [ "ALX", "AL", "QR" ], "Kick": [], "Back to Back Pull": [], "Concealed": [], "Butt": [], "Surface Mount": [], "Mop": [], "Armor": [], "Push": [], "Wall Stops": [] }, "Schlage": { "Mortise": [], "Cylindrical": [ "ALX", "AL", "QR" ], "Deadbolt": [], "Dummy": [], "Interconnected": [], "Cylinders": [] }, "Pemko": { "Sweeps": [ "345AV" ], "Permiter Seal": [ "303AS" ], "Thresholds": [ "170A" ], "Rain Drip": [ "346C" ], "Astragal": [] }, "LCN": { "Surface Mount": [ "4040XP" ], "Concealed": [] }, "Hager": { "Butt": [], "Continuous": [] } }; // 指定要搜索的字段 const targetField = "Continuous"; const filteredArray = []; // 遍历所有品牌对象 for (const brandName in brandData) { const currentBrand = brandData[brandName]; // 检查当前品牌对象是否包含目标字段 if (targetField in currentBrand) { // 将完整的品牌对象存入结果数组,保留品牌名作为键 filteredArray.push({ [brandName]: currentBrand }); } } // 输出结果 console.log(filteredArray);
代码说明
- 遍历原始数据的每个品牌键名,获取对应的品牌对象
- 使用
in操作符检查对象是否包含目标字段 - 符合条件的完整对象会被添加到结果数组中,这里以
{品牌名: 对象}的形式存储,也可以直接存入对象本身(根据需求调整)
运行上述代码后,结果数组会包含Doormerica和Hager的完整对象,与示例需求一致。
内容的提问来源于stack exchange,提问作者JFKMessick
相关产品推荐
相关产品推荐

