so i am trying to create new array from an existing. So basically i have an array that has the structure as shown below. How can i make it so that if i was to add a new object, that would result a new array from that point onwards?
myArray: [{ animal: 'cat', food: 'cupcake' }, { animal: 'dog', food: 'pizza' }, { animal: 'lion', food: 'apple' }, { animal: 'elephant', food: 'spinach' }, ]
So if i was to add a new Object { animal: 'rhino', food: 'banana'}
that result would in a new Array so it would be something like:
newArray: [
{ animal: 'rhino', food: 'banana' }
]
and if i was to add new object in the original array, that would end up in the new Array. Hopefully i have explained it to the best of my abilities.
Use the spread operator for easily creating non-referencing arrays from existing ones.
const myArray = [1, 2, 3] //original array
const myArray2 = [...myArray] //spread operator to create non-referencing array
myArray2.push(4)
console.log(myArray) // [1, 2, 3]
console.log(myArray2) // [1, 2, 3, 4]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.