firasKoubaa
firasKoubaa

Reputation: 6877

How can I convert an array of strings to an array of objects in JavaScript?

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

Answers (3)

DSCH
DSCH

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

Zenoo
Zenoo

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

mpm
mpm

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);

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

Upvotes: 1

Related Questions