Anoop K George
Anoop K George

Reputation: 1735

React Javascript, creating new arrays from existing

I have a array and I need to create new array based on existing.



function CartDetails() {


  const items = [ {"id": 14,'name' :'d'},{ "id": 15,'name' :'c'}]  // FROM THIS ARRAY I NEED TO COPY

 let newarray= [] // RESULTANT ARRAY

useEffect(()=>{

    for (let i in items){ quantity.push(i.id:1)} // MY METHOD OF ARRAY COPY but it is wrong
        },[])

    return (</>)


export default CartDetails

I want to copy the id from parent array and add to new array,

expected result newarray = [{ 14:1},{ 15:1}], here 14 and 15 are parent array ID's and 1 is constant

Upvotes: 0

Views: 2139

Answers (2)

DSCH
DSCH

Reputation: 2366

You can try:

const items = [ {"id": 14,'name' :'d'},{ "id": 15,'name' :'c'}]
const newArray = items.map(item => ({[item.id]:1}));
console.log(newArray);

Upvotes: 3

Anh Tuan
Anh Tuan

Reputation: 1143

const newArr = items.map(item => {
      return {
       [item.id] : 1
      }
    })

check this out

Upvotes: 1

Related Questions