1

Trying to iterate array of objects using es6 as it is very new for me

here is my array of objects

[j]
0: j
$extCollectionIndex: 0
data: {ID: "b7f7ce8b-1455-41b3-ac26-b54916f6718f", userId: "444441", userName: "cjtest.1", email: "cjtest@gmail.com",  …}

need to return or console username

I just tried(map and find )

let obj = records.map(obj => {return obj.data});

console.log(obj)//[object,object]

can any one help me on this

Kon
  • 4,023
  • 4
  • 24
  • 38
R9102
  • 687
  • 1
  • 9
  • 32

3 Answers3

3

Array.prototype.map will return a new array. If you return obj.data you will have an array of objects. You need to be more specific about the data you need.

let obj = records.map(obj => obj.data.userName );
Martial
  • 1,446
  • 15
  • 27
1

Just use your map function over record.data.userName and not just record.data, you can then print it out using join. Or use a forEach loop with a console.log inside.

Working example :

function foo(){
  const records = [
      {
          "data": {
              "ID": "b7f7ce8b-1455-41b3-ac26-b54916f6718f",
              "userId": "444441",
              "userName": "cjtest.1",
              "email": "cjtest@gmail.com"
          }
      },
      {
          "data": {
              "ID": "b7f7ce8b-1455-41b3-ac26-b54916f6718f",
              "userId": "444441",
              "userName": "srtkjrthrt",
              "email": "cjtest@gmail.com"
          }
      },
      {
          "data": {
              "ID": "b7f7ce8b-1455-41b3-ac26-b54916f6718f",
              "userId": "444441",
              "userName": "srthstrj",
              "email": "cjtest@gmail.com"
          }
      },
      {
          "data": {
              "ID": "b7f7ce8b-1455-41b3-ac26-b54916f6718f",
              "userId": "444441",
              "userName": "cjghj1",
              "email": "cjtest@gmail.com"
          }
      }
  ]
  const userList = records.map(record => record.data.userName)
  console.log(userList.join(', '))
}

foo()
Treycos
  • 7,373
  • 3
  • 24
  • 47
0

Here is the output

let obj = records.map(obj => {return obj.data.username});

console.log(obj)//cjtest.1

Thanks you @Weedoze @gaetanoM

R9102
  • 687
  • 1
  • 9
  • 32