Reputation: 727
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
Upvotes: 1
Views: 8676
Reputation: 1562
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 );
Upvotes: 3
Reputation: 7492
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()
Upvotes: 1
Reputation: 727
Here is the output
let obj = records.map(obj => {return obj.data.username});
console.log(obj)//cjtest.1
Thanks you @Weedoze @gaetanoM
Upvotes: 0