【问题标题】:React/JavaScript: Flatten nested array while renaming properties in ReactReact/JavaScript:在 React 中重命名属性时展平嵌套数组
【发布时间】:2018-09-02 20:39:53
【问题描述】:

我有一个需要展平的嵌套数组。例如:

nestedArray = [{ name: 'Dog', obj: {fname:'Bigdog'}, sec{time: 15}},
              { name: 'Bird', obj:{fname: Bigbird'}, sec:{time: 23}}]

但我需要一个如下所示的平面数组:

newArray =[ {id: 1, content: Bigdog, start: 15},
             {id:2, content: Bigbird, start: 23}

【问题讨论】:

  • content: Bigdog 这是一个新变量吗?您是否尝试过编写代码来自己完成此任务?请发布您尝试过的内容
  • 你从哪里得到id
  • id 将是新的。每个条目计数 +1。

标签: javascript reactjs


【解决方案1】:

您可以使用一些破坏并构建新对象。

var array = [{ name: 'Dog', obj: { fname: 'Bigdog' }, sec: { time: 15 } }, { name: 'Bird', obj: { fname: 'Bigbird' }, sec: { time: 23 } }],
    result = array.map(({ obj: { fname: content }, sec: { time: start } }, i) =>
        ({ id: i + 1, content, start })
    );
    
console.log(result);

【讨论】:

    【解决方案2】:

    您可以采用以下方法using map(),来实现此目的:

    var newArray = nestedArray.map(function(item, index) {
    
        return {
            id : (index + 1),
            content : item.obj.fname,
            start : item.obj.sec.time
        }
    })
    

    这里的基本思想是将每个项目从nestedArray“映射”到新的newArray 数组。

    当一个项目被映射时,我们将项目转换为您希望生成的 newArray 中的项目的“形状” - 因此,contentstart 字段基于我们从每个 @ 中提取的数据nestedArray 数组的 987654330@。

    请注意,这假定 id 是基于 nestedArray 中正在处理的项目的当前 index + 1

    有关.map()see this article的更多信息

    希望这会有所帮助!

    【讨论】:

      【解决方案3】:

      只需映射它:

      nestedArray.map((a,idx) => ({ id: idx, content: a.obj.fname, start: a.sec.time}))
      

      【讨论】:

      • 感谢你们的快速回复。在所有三个中,我尝试了带有复选标记的那个。但是,我仍然赞成其他人,因为他们很有帮助。再次感谢!
      【解决方案4】:

      您需要映射输入数组以创建预期的对象。

      nestedArray = [{
          name: 'Dog',
          obj: {
              fname: 'Bigdog'
          },
          sec: {
              time: 15
          }
      }, {
          name: 'Bird',
          obj: {
              fname: 'Bigbird'
          },
          sec: {
              time: 23
          }
      }]
      
      console.log(nestedArray.map((ob, index) => ({id: index + 1, content: ob.obj.fname, start: ob.sec.time})))

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-02-05
        • 2020-11-07
        • 1970-01-01
        • 1970-01-01
        • 2021-10-30
        • 2017-07-20
        • 2020-11-12
        • 2021-06-03
        相关资源
        最近更新 更多