映射嵌套对象

时间:2019-08-01 03:55:36

标签: javascript reactjs

我想在react中映射一个嵌套对象,并将值作为prop传递给要渲染的组件。关于如何映射它或更改对象结构的任何建议将不胜感激。

我的对象

[  
   {  
      "id":1,
      "body":"first obj",
      "nested":[{  
         "id":3,
         "body":"nested obj",
         "nested":null
      }]
   },
   {  
      "id":2,
      "body":"second obj",
      "nested":null
   }
] 

我想将每个对象作为props传递给组件,并且嵌套对象也必须这样做。

组件:

<Foo key = {id} body = {body}/>

渲染:

<Foo/> // id 1
    <Foo/> // id 3
<Foo/> // id 2

我想要实现上面显示的结构。

2 个答案:

答案 0 :(得分:1)

您可以将嵌套地图与React.Fragment一起使用,以避免额外的div。

{
  function createFoos(ele) {
    const a = ele.map(function(({id, body})){
      return <Foo key={id} body={body}/>;
    });
    return ele.nested ? a.concat(createFoos(ele.nested)) : a;
  }

  createFoos(arr);
}

如果您有更多的嵌套数组,我会先创建平面数组,然后简单地在平面数组上进行映射。

nestedObj.map(({ id, body, nested }) =>
   <React.Fragment>
       <Foo id={id} body={body}
       {nested.map(({id, body}) => <Foo id={id} body={body} />)}
  </React.Fragment>
)

答案 1 :(得分:-1)

var filePath = physicalPath + "\\Web.config"; var attributes = File.GetAttributes(filePath); //if you need to update something remove readonly if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { // Make the file RW attributes = attributes &~ FileAttributes.ReadOnly; File.SetAttributes(filePath, attributes); } var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = filePath }; var configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); var appSetting = configuration.AppSettings.Settings["key"].Value; var connectionString = configuration.ConnectionStrings.ConnectionStrings[connectionStringName]; 到嵌套数组中,我建议使用递归:

map