【问题标题】:Map array by nested array object property, to an array of strings通过嵌套数组对象属性将数组映射到字符串数组
【发布时间】:2021-05-13 21:35:01
【问题描述】:

拥有这个包含嵌套数组的对象数组:

let arr = [{
  name: "aaa",
  inputs: [{
    inputName: "input-1",
    groups: [{
      groupName: "group-a"
    }]
  }]
}, {
  name: "bbb",
  inputs: [{
    inputName: "input-2",
    groups: [{
      groupName: "group-b"
    }]
  }]
}];

如何映射它并返回包含 groupName 值的字符串数组,如下所示:

 ['group-a', 'group-b']

【问题讨论】:

    标签: javascript arrays ecmascript-6


    【解决方案1】:

    您可以使用flatMapmap

    const arr = [{name:"aaa",inputs:[{inputName:"input-1",groups:[{groupName:"group-a"}]}]},{name:"bbb",inputs:[{inputName:"input-2",groups:[{groupName:"group-b"}]}]}];
    
    const res = arr.flatMap(
      o => o.inputs.flatMap(
        o => o.groups.map(o => o.groupName)
      )
    );
    
    console.log(res);

    【讨论】:

      【解决方案2】:

      您必须将数组展平两次,然后映射最终结果

      arr.flatMap(x=>x.inputs).flatMap(x=>x.groups).map(x=>x.groupName)
      

      【讨论】:

      • 或 arr.flatMap(x=>x.inputs.flatMap(s=>s.groups.map(x=>x.groupName))))
      【解决方案3】:

      你可以使用Array的map函数。

      let arr = [{
          name: "aaa",
          inputs: [{
            inputName: "input-1",
            groups: [{
              groupName: "group-a"
            }]
          }]
        }, {
          name: "bbb",
          inputs: [{
            inputName: "input-2",
            groups: [{
              groupName: "group-b"
            }]
          }]
        }];
      
        newArr = [] 
      arr.map( element =>{
          console.log( "element" , element )
          newArr.push( element.inputs[0].groups[0].groupName  )
      })
      
      console.log( newArr , "newArr"  )

      【讨论】:

        【解决方案4】:

        您可以循环到数组中的所有元素并将它们的 groupName 添加到数组中,如下所示:

        let arr = [{
            name: "aaa",
            inputs: [{
              inputName: "input-1",
              groups: [{
                groupName: "group-a"
              }]
            }]
          }, {
            name: "bbb",
            inputs: [{
              inputName: "input-2",
              groups: [{
                groupName: "group-b"
              }]
            }]
          }];
        
        let result = [];
        for (let i = 0; i < arr.length; i++) {
            result.push(arr[i].inputs[0].groups[0].groupName);
        }
        console.log(result);

        【讨论】:

          猜你喜欢
          • 2019-05-11
          • 1970-01-01
          • 2021-10-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-05-29
          • 2021-06-23
          • 2023-03-14
          相关资源
          最近更新 更多