Home > Mobile >  Add data to nested object using dynamic keys
Add data to nested object using dynamic keys

Time:05-12

I have an empty object structured like so :

let users = {
  "type1": {
      "group1": {
          "role1": {}
      },
      "group2": {
          "role2": {},
          "role3": {},
          "role4": {}
      },
  },
  "type2": {
      "group1": {
          "role1": {}
      },
      "group2": {
          "role2": {}
      },
      "group3": {
          "role3": {},
          "role4": {}
      }
  }
};

I am then fetching my users with an associated type, group and role for each one. I would like to dynamically add my users to my object above in the right type/group/role combination as they are stored in variables.

I tried something like this but this is wrong:

fetchedUsers.forEach(user => {
  users[user.type][user.group][user.role].push(user.email);
})

Is there a way to do this similar to what I tried ?

CodePudding user response:

You cannot push to an object. Your role is not an array

let users = { 
"type1": { "group1": { "role1": {} },
           "group2": { "role2": {}, "role3": {}, "role4": {}},},
"type2": { "group1": { "role1": {} },
           "group2": { "role2": {}},
           "group3": { "role3": {}, "role4": {}}}};

const fetchedUsers = [
  {"type":"type1","group": "group2", "role":"role3", "email":"[email protected]"},
  {"type":"type2","group": "group1", "role":"role1", "email":"[email protected]"}
];

fetchedUsers.forEach(
  ({type,group,role,email}) => users[type][group][role].email = email
);
console.log(users)

CodePudding user response:

Since users[user.type][user.group][user.role] is an object you can't use push()

If you initialise the empty role structures as arrays it should work.

let users = {
  "type1": {
      "group1": {
          "role1": []
      },
      "group2": {
          "role2": [],
          "role3": [],
          "role4": []
      },
  },
  "type2": {
      "group1": {
          "role1": []
      },
      "group2": {
          "role2": []
      },
      "group3": {
          "role3": [],
          "role4": []
      }
  }
};
  • Related