JavaScript 如何提取嵌套对象中seller键的值并拼接为分号分隔字符串
问题原因
你的代码存在3处核心问题:
- 你声明的数据源变量是
data,但后续遍历的是未定义的digitalData,无法读取到有效数据 - 所有
seller字段都嵌套在data.product.attributes.offer层级下,直接遍历顶层对象的key无法匹配到目标属性 - 将整个
data推入数组的操作属于多余步骤,对提取嵌套字段没有帮助
方案1:适配当前固定结构(性能最优)
如果你的数据结构和示例完全一致,直接定位到offer层级提取即可:
const data = { // 你的原始数据 page: {}, product: { attributes: { condition: 'used', offer: { offer1: { condition: 'used', offerID: '1111', seller: 'Ben', sellerID: 'abc', }, offer2: { condition: 'used', offerID: '2222', seller: 'manu', sellerID: 'def', }, offer3: { condition: 'used', offerID: '3333', seller: 'Ben', sellerID: 'abc', }, }, }, }, }; // 提取offer下所有子对象的seller字段,转小写后拼接 const sellerList = Object.values(data.product.attributes.offer) .map(offer => offer.seller.toLowerCase()) .join(';'); console.log('Offer list :' + sellerList); // 输出:Offer list :ben;manu;ben
方案2:通用递归方案(适配任意嵌套结构)
如果后续数据结构可能调整,seller字段的嵌套层级不固定,可以用递归函数全局收集所有seller的值:
const data = { /* 你的原始数据 */ }; // 递归收集对象中所有指定key的值 function collectTargetKey(obj, targetKey) { let res = []; for (const [key, val] of Object.entries(obj)) { if (key === targetKey) res.push(val); if (typeof val === 'object' && val !== null) { res = res.concat(collectTargetKey(val, targetKey)); } } return res; } const sellerList = collectTargetKey(data, 'seller') .map(name => name.toLowerCase()) .join(';'); console.log('Offer list :' + sellerList);
内容的提问来源于stack exchange,提问作者Joris ALEXANDRE
相关产品推荐
相关产品推荐

