There is such an object:

var rooms = { '/#IHT50E5Ds0jZdY_RAAAA': { room_name: 'NEW_ROOM1', name_owner: 'GUEST1' }, '/#NqtUF7Y3VZtH4OaVAAAC': { room_name: 'NEW_ROOM2', name_owner: 'GUEST2' } } 

How can you get from it like this:

 var full_rooms = { '/#IHT50E5Ds0jZdY_RAAAA': { room_name: 'NEW_ROOM1', name_owner: 'GUEST1', users: 1 }, '/#NqtUF7Y3VZtH4OaVAAAC': { room_name: 'NEW_ROOM2', name_owner: 'GUEST2', users: 1 } } 

Those. add a property to every object?

I just can’t get used to the JS syntax when working with objects, because of this, nothing happens :(

  • Break the task into simpler ones. First, you need to go through all the values ​​of your dictionary. Then add each property. Individually, the answer to these subtasks is easier to find than together. - Pavel Mayorov
  • I reached the first point. for (var room in rooms) { 'что делать тут, не знаю '} - Literate
  • Well, the second elementary in general is obj.users = 1 , where obj is the object obtained in the first paragraph. - Pavel Mayorov
  • Only here the first point would be a little wrong. It is necessary to get the values ​​in the dictionary - and you got the keys. - Pavel Mayorov
  • Ugh, how can you properly disassemble the room object? I read the answer to this question, and what of this will work? - Literate

1 answer 1

changed:

  var rooms = { '/#IHT50E5Ds0jZdY_RAAAA': { room_name: 'NEW_ROOM1', name_owner: 'GUEST1' }, '/#NqtUF7Y3VZtH4OaVAAAC': { room_name: 'NEW_ROOM2', name_owner: 'GUEST2' } } var full_rooms= {}; for (var item in rooms){ full_rooms[item] = rooms[item]; full_rooms[item].users = 1; } console.log(full_rooms); 

if you want to keep the source:

  var rooms = { '/#IHT50E5Ds0jZdY_RAAAA': { room_name: 'NEW_ROOM1', name_owner: 'GUEST1' }, '/#NqtUF7Y3VZtH4OaVAAAC': { room_name: 'NEW_ROOM2', name_owner: 'GUEST2' } } var full_rooms= {}; for (var item in rooms){ full_rooms[item] = {}; for(var x in rooms[item]){ full_rooms[item][x] = rooms[item][x]; } full_rooms[item].users = 1; } console.log(full_rooms); console.log(rooms); 
  • There is no object like full_rooms. It needs to be created from rooms - Literate
  • item in this case is a string, the name of the property, and not the value - Grundy
  • @Literate put a specific question ... "duplicate object with a new property (field)" .. - C.Raf.T
  • Yes OK. Apparently not properly formulated the question. Thanks for the answer, I will try not to be stupid again. - Literate
  • @Literate is more careful - if you need a copy of the original structure with a new field, then take into account that a new field appears in this code not only at the copy. - Pavel Mayorov