-2

My objective is to create a JSON file like this

{
  "empList": {
    "1234": {
      "fullName": "Joe Tester",
      "city": "Austin",
      "state": "TX"
    },
    "2344": {
      "fullName": "Tim Developer",
      "city": "Dallas",
      "state": "TX"
    }
  }
}

I have a list of employees as a flat structure in a employee string array (id, fullname, city, state). How can I write the JavaScript code to create json structure above?

ThS
  • 4,597
  • 2
  • 15
  • 27
AAbcDev
  • 13
  • 4
  • 1
    Can you post your input array? – obscure Aug 08 '19 at 22:16
  • 3
    Have you done any research on this? For example, I would use a search engine and type "Convert object to JSON in JavaScript". – halfer Aug 08 '19 at 22:16
  • Possible duplicate of [Convert JS object to JSON string](https://stackoverflow.com/questions/4162749/convert-js-object-to-json-string) – halfer Aug 08 '19 at 22:26

2 Answers2

-1

var data = {
  "empList": {
    "1234": {
      "fullName": "Joe Tester",
      "city": "Austin",
      "state": "TX"
    },
    "2344": {
      "fullName": "Tim Developer",
      "city": "Dallas",
      "state": "TX"
    }
  }
}

JSON.stringify(data);
ThS
  • 4,597
  • 2
  • 15
  • 27
M1R4L3M
  • 1
  • 3
  • you missed the `=`, I did for you. FYI, the autosnippet box has a format button that help formatting your code so it'll be more readable. – ThS Aug 08 '19 at 22:23
-1

Something like:

var flatArray = [
  {id:1234, fullName:"Joe Tester", city:"Austin", state:"TX"},
  {id:2234, fullName:"Tim Developer", city:"Dallas", state:"TX"},
]

var obj = {empList:{}};

for(var i = 0; i < flatArray.length; i++) {
  var entry = flatArray[i];
  obj.empList[entry.id] = {
    fullName:entry.fullName,
    city:entry.city,
    state:entry.state
  }
}

console.log(obj);
Chris HG
  • 1,412
  • 16
  • 20