我有一些JS对象,每个对象都有一个孙子属性,称为“产品”。
例如ecommerce.add.products, ecommerce.remove.products, ecommerce.detail.products, ecommerce.checkout.products, ecommerce.purchase.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'/]未定义
不管父母的名字如何,我如何访问嵌套的孙子“产品”对象?
答案 0 :(得分:3)
您可以简单地遍历ecom
对象并检查detail','add','remove','checkout','purchase'
对象上是否存在以下道具ecom
,
类似的东西
let outerKey = ['detail','add','remove','checkout','purchase']
let foundProducts = outerKey.reduce((op,inp) => {
if(ecom[inp] && ecom[inp].products && ecom[inp].products.length){
op.push(ecom[inp].products)
}
return op
},[])
使用正则表达式尝试
var ecomProducts = ecom[('detail'|'add'|'remove'|'checkout'|'purchase')]['products'];
不,这不是正则表达式,这只是逻辑或,因此您始终以ecom['checkout']['products']
答案 1 :(得分:1)
假设您有一个这样的对象:
ecommerce = {
add: { products: ['add products'] },
remove: { products: ['remove'] },
detail: { products: ['prod details'] },
checkout: { products: ['checkout'] },
purchase: { products: ['purchase'] }
};
for( var x in ecommerce )"products" in ecommerce[ x ] ?
console.log( ecommerce[ x ].products ) : 0;
无论从哪棵树上摘下,您都无法捡起苹果-您需要参观其中的树和树枝...
最简单,最可移植的方法是拥有一个使用以下表达式的函数::
for( var x in ecommerce )"products" in ecommerce[ x ] ?
console.log( ecommerce[ x ].products ) : 0;
并运行无错误。