【发布时间】:2019-05-27 01:16:31
【问题描述】:
我有一些 JS 对象,它们每个都有一个名为“products”的孙子属性。
例如ecommerce.add.products, ecommerce.remove.products, ecommerce.detail.products, ecommerce.checkout.products, ecommerce.purchase.products
无论上面的特定对象是什么,我都想访问 products 数组。
尝试使用正则表达式:
var ecomProducts = ecom[('detail'|'add'|'remove'|'checkout'|'purchase')]['products'];
TypeError: ecom[(((("detail" | "add") | "remove") | "checkout") | "purchase")] 未定义
var ecomProducts = ecom[/'detail'|'add'|'remove'|'checkout'|'purchase'/]['products'];
TypeError: ecom[/'detail'|'add'|'remove'|'checkout'|'purchase'/] 未定义
无论父母姓名如何,我如何访问嵌套的孙子“产品”对象?
【问题讨论】:
-
描述上述内容的正则表达式是:/ecommerce.[add|remove|detail|checkout|purchase].products/。但是如果您需要 access - 正则表达式可能还不够,因为您必须 check 应用哪种模式。
-
最终更通用的方式:
Object.values(ecommerce).find(item => typeof item === 'object' && item !== null && !!item.products)
标签: javascript arrays regex string regex-group