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: "[email protected]",  …}

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

6
  • can you post the whole array? Commented Jan 4, 2019 at 14:02
  • ...obj.data.userName Commented Jan 4, 2019 at 14:03
  • What's wrong with map ? Commented Jan 4, 2019 at 14:03
  • Your question is pretty vague, but I'd assume you need something like for (let object of records) { console.log(object.data.username); } Commented Jan 4, 2019 at 14:03
  • 3
    records.map(obj => obj.data.username); Commented Jan 4, 2019 at 14:04

3 Answers 3

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 );
Sign up to request clarification or add additional context in comments.

Comments

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": "[email protected]"
          }
      },
      {
          "data": {
              "ID": "b7f7ce8b-1455-41b3-ac26-b54916f6718f",
              "userId": "444441",
              "userName": "srtkjrthrt",
              "email": "[email protected]"
          }
      },
      {
          "data": {
              "ID": "b7f7ce8b-1455-41b3-ac26-b54916f6718f",
              "userId": "444441",
              "userName": "srthstrj",
              "email": "[email protected]"
          }
      },
      {
          "data": {
              "ID": "b7f7ce8b-1455-41b3-ac26-b54916f6718f",
              "userId": "444441",
              "userName": "cjghj1",
              "email": "[email protected]"
          }
      }
  ]
  const userList = records.map(record => record.data.userName)
  console.log(userList.join(', '))
}

foo()

Comments

0

Here is the output

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

console.log(obj)//cjtest.1

Thanks you @Weedoze @gaetanoM

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.