0

What I'm trying to do is copy object using object-array with map api.
like below. decomposite the array inside of an object, and copy.

 const obj = [{id: 1, arr: ['a', 'b', 'c']}];


//expected result
  const result = [
    {id: 1, arr: 'a'},
    {id: 1, arr: 'b'},
    {id: 1, arr: 'c'},
  ];

and also setState.

  const [obj2, setObj2] = useState([{id: 1, arr: ['a', 'b', 'c']}]);

  //Both ways were invalid
  //setObj2(...obj2, obj2.arr.map(rr => obj2:rr)) 
  //setObj2(...obj2, obj2.arr : obj2.arr.map(rr => rr))

//expected result
console.log(obj2);
=> [
    {id: 1, arr: 'a'},
    {id: 1, arr: 'b'},
    {id: 1, arr: 'c'},
   ];

I have no idea how to make it

2
  • obj is an array with only one element or maybe more? Commented Apr 29, 2021 at 6:34
  • it can be more then one Commented Apr 29, 2021 at 6:37

3 Answers 3

1

You can achieve this using reduce:

 const obj = [{id: 1, arr: ['a', 'b', 'c']}];

const result = obj.reduce((acc, cur) => {
   const { id, arr } = cur;
   const res = arr.map(x => ({ id, arr: x }));
   return acc.concat(res);
}, []);

console.log(result);

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

Comments

1

You can use flatMap() like this:

const data = [{
    id: 1,
    arr: ['a', 'b', 'c']
  },
  {
    id: 2,
    arr: ['d', 'be', 'f']
  }
];


const result = data.flatMap(({id, arr}) => {
  return arr.map(item => ({id, arr: item}));
});

console.log(result);

Comments

0

It can be done like this:

setObj2(obj2.map(item => {
   x = []
   item.arr.forEach(item2 => x.push({id:item.id, arr:item2}));
   return x;
}));

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.