-3

i have an array like this coming back response from the server:

[
    "111",
    "1010",
    "111",
    "1010",
    "1010"
]

i want to convert it into a JavaScript JSON like this:

[
 {
    "branch":  "111"

 },
 {
    "branch":  "1010"
 },
 {
    "branch":  "111"
 },
 {
    "branch":  "1010"
 },
 {
    "branch":  "1010"
 }
]
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
Aqib Zaman
  • 265
  • 2
  • 8
  • 17
  • 2
    Possible duplicate of [What is the concept of Array.map?](https://stackoverflow.com/questions/17367889/what-is-the-concept-of-array-map) – Joe Clay Feb 27 '19 at 08:45
  • 1
    thats not a valid json.. -> check colons before `}` - I edited your question.. – iLuvLogix Feb 27 '19 at 08:51

2 Answers2

3

You could map a short hand property.

var array = ["111", "1010", "111", "1010", "1010"],
    result = array.map(branch => ({ branch }));

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

You can use map() to create a new array with the results of calling a provided function on every element in the calling array

var arr = [
    "111",
    "1010",
    "111",
    "1010",
    "1010"
]

var res = arr.map(i => ({'branch': i}));
console.log(res);
Mamun
  • 66,969
  • 9
  • 47
  • 59