-2

I have an array of elements I want to map to a new array of objects with a key as a name.

let array = ["abc", "def", "xyx"]

Expected Output

let array1 = [{name: "abc"}, {name: "def"}, {name: "xyz"}]
Not A Bot
  • 2,474
  • 2
  • 16
  • 33
Siva Sai
  • 319
  • 2
  • 5
  • 21
  • See this answer: https://stackoverflow.com/questions/19590865/from-an-array-of-objects-extract-value-of-a-property-as-array – FD3 Dec 10 '21 at 10:20

3 Answers3

0

You can use array.map:

let newArray = array1.map((value) => ({name: value});
Tom
  • 1,158
  • 6
  • 19
0

let arr = ['a', 'b', 'c'];

let newArr = arr.map(el => ({ name: el }));

console.log(newArr);
Not A Bot
  • 2,474
  • 2
  • 16
  • 33
arm
  • 145
  • 1
  • 5
  • 1
    I was lazy writing out the string values, but it actually results in an array of objects, just as the expected output is supposed to be. – arm Dec 10 '21 at 10:21
0

you can use map() function for that,

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

    let array = ["abc", "def", "xyx"]
    const array1 = array.map( data => { 
    return {name:data}
    })
    /* this code will also work,if you dint specify the properties name 
    by default it will be the variable's name. In this case 'name' */
     const array2 = array.map( name => { 
    return {name}
    })
    console.log(array1)
    console.log(array2)
hasankzl
  • 666
  • 4
  • 16