chidananda
chidananda

Reputation: 141

structure format from array to array of object

I'm trying to form the structure like expectedOutput by iterating input array,but unable to form structure

let input = ["lim","kim"]
let expectedOutput = [{id:"lim"},{id:'kim'}]

let newArr = input.reduce((acc,cur,i)=> {
acc['id'] = cur;
return acc;
},[])
console.log(newArr)

Upvotes: 1

Views: 37

Answers (4)

Tigran Abrahamyan
Tigran Abrahamyan

Reputation: 776

Change this line

acc['id'] = cur;

Into

acc['id'] = acc.push({ id: cur });

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386578

You could map an object with a short hand property.

const
    input = ["lim", "kim"],
    result = input.map(id => ({ id }));

console.log(result);

Upvotes: 2

Maheer Ali
Maheer Ali

Reputation: 36574

You can just use map()

let input = ["lim","kim"]
const res = input.map(x => ({id: x}));
console.log(res)

Upvotes: 0

Wais Kamal
Wais Kamal

Reputation: 6180

I have no idea why you are using reduce(). You can use Array.map():

let input = ["lim","kim"]
let expectedOutput = [{id:"lim"},{id:'kim'}]

let newArr = input.map(item => {
  return {id: item};
});
console.log(newArr);

Upvotes: 0

Related Questions