-1

Now I have object like this

  let arr = [{name:'first'},{name:'first1'}]

Exprected

  [{value:'first'},{value:'first1'}]

My attempt

  let result = arr.map(el=>{
  const {name, ...other} = el;

  return {value: el.name, ...other}
})

2 Answers2

2

you can do it that way!

let arr = [{name:'first'},{name:'first1'}]  //{value: 'first'}

let result = arr.reduce((acc,el)=>{
  return [...acc, {'value' : el.name}]
},[])
Taimoor Qureshi
  • 620
  • 4
  • 14
  • What is wrong with OP's code. Why use `reduce` instead of `map` when the input and the output have the same number of elements? – adiga Apr 27 '21 at 07:14
  • It's a matter of preference if the length of output and input array is the same. otherwise reduce is an aggregate function (return a single value in the end), map returns an array of transformed values. – Taimoor Qureshi Apr 27 '21 at 07:32
0

You can transform the data using Array.prototype.map.

let arr = [{name:'first'},{name:'first1'}]
let result = arr.map(x => {return {value: x.name}});
console.log(result);
Ayaz
  • 2,111
  • 4
  • 13
  • 16