0

I want to return a new array but take the property value to become property name.

const temp = [
  {name: 'james'},
  {name: 'ally'}
]

const new = temp.map(obj => ({
    `${obj.name}`: null
}))

Obviously it doesn't work this way. Any clue? https://jsfiddle.net/qg8ofom1/

Alexander Elgin
  • 6,796
  • 4
  • 40
  • 50
Jane Emelia
  • 477
  • 2
  • 5
  • 11

2 Answers2

1

const temp = [
  {name: 'james'},
  {name: 'ally'}
];

const newObj = temp.map(obj => ({
    [obj.name]: null
}));

console.log(newObj);
Alexander Elgin
  • 6,796
  • 4
  • 40
  • 50
1

couple of things are incorrect

  1. new is a reserved word. You can not use it to declare a variable
  2. missing brackets around your temp array's items
  3. limited in what you can use as a key: https://stackoverflow.com/a/6500668/534056

try this:

const temp = [
  { name: 'james' }, 
  { name: 'ally' }
]

const newObject = temp.map(obj => ({
  [obj.name]: null
}))

console.log(newObject)

That's ES6, so if you need to you can use bracket notation to assign properties

const temp = [
  { name: 'james' },
  { name: 'ally' }
]

const new1 = temp.map(obj => {
  var x = {}
  x[obj.name] = null
  return x
})

console.log(new1)
ptpaterson
  • 9,131
  • 4
  • 26
  • 40