Converting Array of Strings into Key Value Pair


I have an string from backend source, of format:

numbers: "1123763449056714753, 1123764853364097024, 1123770213739241473..."

I want to convert it into key-value pair something form so that I can map over these ids for my individual item div:

["numbers": [ 
              {"id":1123763449056714753 }, 
              {"id":1123764853364097024 },
              {"id":1123770213739241473 },
             ....
            ]
]

or

[                 {"id":1123763449056714753 }, 
                  {"id":1123764853364097024 },
                  {"id":1123770213739241473 },
                 ....

    ]

I tried using forEach()/ map() but gets error as undefined. Also I am not sure whether it is a collection of string or array of strings Please help

You could split the string and map the objects by keeping the strings (who are larger than allowed integer values).

var object = { numbers: "1123763449056714753,1123764853364097024,1123770213739241473,1123771975162368003" },
    numbers = object.numbers.split(',').map(id => ({ id }));

console.log(numbers);
.as-console-wrapper { max-height: 100% !important; top: 0; }


var arr = ["1123763449056714753","1123764853364097024","1123770213739241473","1123771975162368003"];
var newArr = [];
for (var i = 0; i < arr.length; i++) {
    var obj = {};
    obj.id = arr[i];
    newArr.push(obj);
}
console.log(newArr)


You can do something like this.

var data = {"numbers":"1123763449056714753,1123764853364097024,1123770213739241473,1123771975162368003"};

data.numbers = data.numbers.split(',').reduce((res, id) => [...res, {id}], []);

You can split the object then map it and return the structure you want :

const obj = {
  "numbers": "1123763449056714753,1123764853364097024,1123770213739241473,1123771975162368003..."
}


const res = {
  numbers: [
    obj.numbers.split(",").map(el => ({
      id: el
    }))
  ]
}

console.log(res);


One thing you could do is get the numbers as an array:

var obj = {
  "numbers": "1123763449056714753,1123764853364097024,1123770213739241473,1123771975162368003"
};

var result = obj.numbers.split(',').reduce((acc, num) => {
  acc.push({ id: num });
  return acc;
}, []);

console.log(result)

or as @briosheje mentioned you could also use map:

var result = obj.numbers.split(',').map(num => ({id: num}));

The result would look like this:

[{"id":"1123763449056714753"},{"id":"1123764853364097024"},{"id":"1123770213739241473"},{"id":"1123771975162368003"}]

As per your data, you can just split the numbers string using "," and loop through it to perform the transform, like

var data = {"numbers":"1123763449056714753,1123764853364097024,1123770213739241473,1123771975162368003"};
var numbers_arr = data.numbers.split(",");
var result = {
  "numbers":[]
};
for(var i=0;i<numbers_arr.length;i++){
 var tempObj = {
    "id":parseInt(numbers_arr[i])
  };
  result.numbers.push(tempObj)
}

console.log(JSON.stringify(result));