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

1
  • 2
    map doesn't change the array. It returns a new version of it. Commented Oct 5, 2018 at 9:51

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.