0

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

2 Answers 2

3

You can try:

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

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

2 Comments

Thanks, How do {item.id} method gets wrong ? and [item.id] is the correct way
Since you want to create an object item, you have to use the curly braces. Then assign the ID as the key - i.e. to the left of the colon and the value to its right. I used square brackets on the left hand side as the key is dynamic - meaning each iteration will provide a different key and it's not hard coded. ({age: 20} vs {[currentProperty]: some value})
1
const newArr = items.map(item => {
      return {
       [item.id] : 1
      }
    })

check this out

2 Comments

var newItems = [...items].map(i => ({[i.id]: 1}))
why you need [...items] . basicly, map not modify your own array (items)

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.