0

Having this array of objects containing nested arrays:

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

How to map it and return an array of strings containing the groupName value, like this:

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

4 Answers 4

3

You can use flatMap and map

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);

Sign up to request clarification or add additional context in comments.

Comments

0

You must flat your arrary twice and then map the final result

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

1 Comment

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

You may use map function of Array.

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"  )

Comments

0

you can loop to all elements in the array and add their groupName to an array like so :

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.