1

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"]));

1
  • 2
    Try changing the one line in the loop: result[item] = {[key] : item}; Commented Mar 6, 2021 at 14:57

2 Answers 2

3

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"]));

Sign up to request clarification or add additional context in comments.

Comments

0
employes.reduce((obj, emp) => {
    if(typeof(obj) === "string") {
        var temp = {}
        temp[obj] = {id:obj}
        obj = temp;
    }
    obj[emp] ={id:emp};
    return obj;
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.