Javascript 将嵌套的json项名称传递给函数
我用对象Account和Category嵌套了json数据。Category在Account json数据中。我将默认列传递给map函数,它将创建我的列。但如果我传递了Category.Name,我将无法在屏幕上看到。我如何将嵌套数据属性名称传递给此函数Javascript 将嵌套的json项名称传递给函数,javascript,arrays,json,reactjs,react-jsx,Javascript,Arrays,Json,Reactjs,React Jsx,我用对象Account和Category嵌套了json数据。Category在Account json数据中。我将默认列传递给map函数,它将创建我的列。但如果我传递了Category.Name,我将无法在屏幕上看到。我如何将嵌套数据属性名称传递给此函数 //Default Columns: this.defaultColumns = ["Name","Limit","Category.Name"]; //My Function: that.props.results.map(fu
//Default Columns:
this.defaultColumns = ["Name","Limit","Category.Name"];
//My Function:
that.props.results.map(function(rowData){
return (
<tr>
{that.props.defaultColumns.map(function (column) {
return (
<td>{rowData[column]}</td>
);
</tr>})}
我不确定您是否知道,但您无法通过
rowData['Category.Name']
访问嵌套属性。这将尝试访问名为Category.name
的属性,也就是说,如果您有一个类似
{
'Cateogry.Name': 42
}
可以做的一件事是为每个列指定渲染函数。这些渲染函数定义如何访问每列的数据。例如:
var columnRenderer = {
Name: x => x,
Limit: x => x,
Category: x => x.Name
};
然后,假设您的列为
//Default Columns:
this.defaultColumns = ["Name","Limit","Category"];
您可以使用
that.props.results.map(
rowData =>
<tr>
{that.props.defaultColumns.map(
column => <td>{columnRenderer(rowData[column])}</td>
)}
</tr>
);
that.props.results.map(
行数据=>
{that.props.defaultColumns.map(
column=>{columnRenderer(rowData[column])}
)}
);
(注意:我在这里使用的是ES6特性的箭头函数,因此如果您使用jsx命令行工具,则必须传递
--harmony
选项,或者使用普通函数)。JSON的示例比描述更清晰。
在JavaScript中不是有效的语法,除非是React的.jsx。您的意思是返回字符串吗?很抱歉,复制粘贴问题。在我的屏幕中,我可以看到名称-限制列,但看不到类别。名称列嗯,您没有名称为类别的属性。名称为,只有名称为类别的属性。您希望rowData['Category.Name']
神奇地访问嵌套属性吗?但是我在Category中有Name,我想显示这个日期。我在网格中使用它。它有很多页面。我如何编写这个通用版本?您是说您有其他数据,不想为每个列编写渲染器吗?或者你觉得这个解决方案有什么特别之处?是的,我不想为每一列都编写渲染器。[“名称”、“限额”、“类别”];我希望像这样传递列名,方法将处理此问题。
that.props.results.map(
rowData =>
<tr>
{that.props.defaultColumns.map(
column => <td>{columnRenderer(rowData[column])}</td>
)}
</tr>
);