Skip to content
Advertisement

How to create an object dynamically using JavaScript?

I’m trying to create a new object from an array of strings, but I’m not able to create the desired object correctly.

I’m trying to create an object like:

{
  "Employee1": {
    "id": "Employee1"
  },
  "Employee2": {
    "id": "Employee2"
  }
}

Here’s my code:

function listToItemById(qsList, key = "id") {
  const result = {};
  qsList.forEach((item) => {
    result[item][key] = item;
  });

  return result;
}

console.log(listToItemById(["Employee1", "Employee2", "Employee3", "Employee4", "Employee5", "Employee6", "Employee7", "Employee8"]));

Advertisement

Answer

Yes.

First, we have to set result[item] to {} (a new, empty object):

function listToItemById(qsList, key = "id") {
  const result = {};

  qsList.forEach((item) => {
    result[item] = {};
    result[item][key] = item;
  });

  return result;
}

console.log(listToItemById(["Employee1", "Employee2", "Employee3", "Employee4", "Employee5", "Employee6", "Employee7", "Employee8"]));
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement