简体   繁体   English

如何遍历ES6中的对象数组

[英]How to iterate through array of objects in ES6

Trying to iterate array of objects using es6 as it is very new for me 尝试使用es6迭代对象数组,因为这对我来说是很新的

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 谁可以帮我这个事

Array.prototype.map will return a new array. Array.prototype.map将返回一个新数组。 If you return obj.data you will have an array of objects. 如果返回obj.data ,则将有一个对象数组。 You need to be more specific about the data you need. 您需要对所需的数据更加具体。

let obj = records.map(obj => obj.data.userName );

Just use your map function over record.data.userName and not just record.data , you can then print it out using join . 只需在record.data.userName使用map函数,而不仅仅是record.data即可,然后可以使用join将其打印出来。 Or use a forEach loop with a console.log inside. 或使用带有console.log的forEach循环。

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

Here is the output 这是输出

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

console.log(obj)//cjtest.1

Thanks you @Weedoze @gaetanoM 谢谢@Weedoze @gaetanoM

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM