1

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)

1
  • Try let output = input.map((name) => ({ id: name })); To edit your code - acc.push({ id: curr }); Commented Jan 5, 2021 at 8:21

4 Answers 4

2

You could map an object with a short hand property.

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

console.log(result);

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

Comments

0

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

Comments

0

You can just use map()

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

Comments

0

Change this line

acc['id'] = cur;

Into

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.