如何获取指定对象(cat、dog、bird)的所有名称?JavaScript技术问询
解决方法:获取指定动物产品的名称
Got it, let's tweak this code to perfectly fit your need—only grabbing names for cat, dog, and bird products. The original recursive logic was overcomplicating things (it would end up pulling in keys like count or price too), so here's a clean, targeted solution:
完善后的代码
var storage = [ {cat: {name: "Garfield", count: 3443, price: 1000}}, {bird: {name: "Eagle", count: 4042, price: 3000}}, {dog: {name: "Rex", count: 1488, price: 2000}} ]; function getTargetProductNames(storage) { // 定义我们要筛选的目标产品类型 const targetTypes = ['cat', 'dog', 'bird']; const productNames = []; for (const item of storage) { // 取出当前项的唯一动物类型(你的数据结构里每个item只有一个动物键) const animalType = Object.keys(item)[0]; // 检查是否是我们需要的类型,是就提取名称 if (targetTypes.includes(animalType)) { productNames.push(item[animalType].name); } } return productNames; } // 测试调用,会输出 ["Garfield", "Eagle", "Rex"] console.log(getTargetProductNames(storage));
逻辑说明
- 先明确目标类型集合,避免提取无关产品;
- 遍历存储数组时,用
Object.keys(item)[0]快速获取每个项对应的动物类型(适配你的单键item结构); - 通过
includes()判断类型是否符合要求,精准提取对应的name属性; - 相比原递归写法,这个实现更贴合你的数据结构,效率更高且结果不会出错。
如果之后你的数据结构可能出现一个item包含多个动物类型的情况,也可以调整成下面的版本,确保不会漏过任何目标产品:
function getTargetProductNames(storage) { const targetTypes = ['cat', 'dog', 'bird']; const productNames = []; for (const item of storage) { // 遍历当前item的所有键,确保不会错过多个目标类型 for (const key of Object.keys(item)) { if (targetTypes.includes(key)) { productNames.push(item[key].name); } } } return productNames; }
内容的提问来源于stack exchange,提问作者Igor Shvets
相关产品推荐
相关产品推荐

