Reputation: 6877
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
Upvotes: 0
Views: 66
Reputation: 2396
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;
});
Upvotes: 0
Reputation: 12880
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);
Upvotes: 1
Reputation: 20155
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);
Upvotes: 1