如何让MUI X Data Grid的valueGetter读取数组中指定对象的数据?
解决MUI X Data Grid中从Woocommerce属性数组获取指定值的问题
问题根源
你之前的valueGetter写法完全错误,因为**attributes是数组而非对象**,不能直接通过箭头函数或属性名索引的方式获取元素。params.row.attributes[name =>'Farbe']这种写法不符合数组查找语法,导致返回undefined,进而触发Cannot read properties of undefined (reading 'option')错误。
正确实现方式
使用数组的find()方法遍历attributes数组,筛选出name等于"Farbe"的对象,再获取其option值。同时添加空值保护,避免因数据缺失导致报错:
export const VariationColumns = [ { field: 'id', headerName: 'Id', type: 'int', width: 100 }, { field: 'sku', headerName: 'SKU', type: 'string', width: 200 }, { field: 'farbe', headerName: 'Farbe', type: 'string', width: 500, valueGetter: (params) => { // 空值保护:确保attributes存在且是数组 if (!params.row?.attributes || !Array.isArray(params.row.attributes)) { return ''; } // 查找name为"Farbe"的属性对象 const farbeAttr = params.row.attributes.find(attr => attr.name === 'Farbe'); // 返回option值,找不到则返回空字符串 return farbeAttr?.option || ''; } }, ];
额外优化建议
如果需要多次查找不同名称的属性,可以把查找逻辑抽成复用函数:
const getAttributeOption = (attributes, targetName) => { if (!attributes || !Array.isArray(attributes)) return ''; const attr = attributes.find(item => item.name === targetName); return attr?.option || ''; }; export const VariationColumns = [ // ...其他列 { field: 'farbe', headerName: 'Farbe', type: 'string', width: 500, valueGetter: (params) => getAttributeOption(params.row.attributes, 'Farbe') }, { field: 'material', headerName: 'Material', type: 'string', width: 500, valueGetter: (params) => getAttributeOption(params.row.attributes, 'Material') }, ];
为什么你的其他尝试也失败
params.row.attributes[name =>'Farbe'].option.value:语法错误,数组不能用箭头函数作为索引params.row.attributes.name['Farbe'].option:attributes是数组,没有name属性,直接访问会返回undefinedparams.row.attributes.name['Farbe'].option.value:同上,且多了不必要的.value(原数据中option本身就是字符串值)
内容的提问来源于stack exchange,提问作者netbird
相关产品推荐
相关产品推荐

