0

I have this array:

myArray = ["AAA","BBB",...,"ZZZ"];

I want to convert it to an array of objects. Something like this:

myArray = [
    {
        "Id": "111",
        "Value": "AAA"
    },
    ....
    {
        "Id": "111",
        "Value": "ZZZ"
    },
];

I've tried to use the map method like this:

myArray.map(str => {
    let obj = {};
    obj['Id'] = '111';
    obj['Value'] = str;
});

But console.log(myArray) outputs this:

undefined

Krisztián Balla
  • 19,223
  • 13
  • 68
  • 84
firasKoubaa
  • 6,439
  • 25
  • 79
  • 148

3 Answers3

1

You need to return a result from the mapper function.

let myNewArray = myArray.map( str => {
      let obj = {};
      obj['Id'] = '111' ;
      obj['Value'] = str ;
      return obj;
});
// or 
let myNewArray = myArray.map( str =>  ({Id:111,Value:str}) );
// parenthesis are needed to remove the ambiguity with `{}`
console.log(myNewArray);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Using_map_to_reformat_objects_in_an_array

mpm
  • 20,148
  • 7
  • 50
  • 55
1

Here is the clean ES6 one liner version using Array#map

const data = myArray = ["AAA","BBB","ZZZ"];

let result = data.map(e => ({'Id': '111', 'Value': e}));
console.log(result);
Zenoo
  • 12,670
  • 4
  • 45
  • 69
0

You need to return the result into a new variable, or your existing one, as map create a new array and doesn't change the one you are iterating over.

    const myArrayOfObjects = myArray.map( str => {
      let obj = {};
      obj['Id'] = '111' ;
      obj['Value'] = str ;
      return obj;
});
DSCH
  • 2,146
  • 1
  • 18
  • 29