简体   繁体   中英

Print array of object of array javascript

I am so confused about some datas. I am working with vanilla js. I have an array like this.

rooms=[];
rooms.push({"room":"room1","users":[{"name":"arif"},{"name":"ozgur"}]});
rooms.push({"room":"room2","users":[{"name":"mehmet"},{"name":"hürol"}]});

I want to print users of room1. I have tried

let activeroom = rooms.filter(room => room.room === "room1");
console.log(activeroom.users.toString()); 

But it didnt work. How can I access to names? Thank you.

Use find instead of filter

 rooms=[]; rooms.push({"room":"room1","users":[{"name":"arif"},{"name":"ozgur"}]}); rooms.push({"room":"room2","users":[{"name":"mehmet"},{"name":"hürol"}]}); let activeroom = rooms.find(room => room.room === "room1"); console.log(activeroom.users);

your filter is right, but activeroom is array not object and you can't call .toString() for object use JSON.stringify() instead.

 rooms=[]; rooms.push({"room":"room1","users":[{"name":"arif"},{"name":"ozgur"}]}); rooms.push({"room":"room2","users":[{"name":"mehmet"},{"name":"hürol"}]}); let activeroom = rooms.filter(room => room.room === "room1"); console.log(JSON.stringify(activeroom)); console.log(JSON.stringify(activeroom[0].users)); // [0] select first index of object

You can do something like this:

let activeRooms = [];

rooms.forEach(eachRoom => {
  if (eachRoom.room === 'room1) {
      activeRooms.push(eachRoom);
  }
});

console.log('Active rooms array ==>', activeRooms);

// if you want to use your way of doing, implement filter inside the foreclosure. It will work. 

Room.room is not a property .. room is an array. So you'll have to loop through every room obj

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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