I have an array like this:
var oldArray = [{'value': '1', 'label': 'a'}, {'value': '2', 'label': 'b'}]
what I want is using spread operator add a new object at the beginning of that array:
BTW this works:
var oldArray = [{'value': '1', 'label': 'a'}, {'value': '2', 'label': 'b'}]
var newObj = {'value': 'all', 'label': 'all'}
var result = [newObj, ...oldArray]
But generates a key "newObj" like this:
var oldArray = [newObj : {'value': 'all', 'label': 'all'}, 0: {'value': '1', 'label': 'a'}, 1:{'value': '2', 'label': 'b'}]
And I want the key to be auto generated like if I do this:
var result = [{'value': 'all', 'label': 'all'}, ...oldArray]
And imagine the result is this:
var oldArray = [newObj : {0: 'all', 'label': 'all'}, 1: {'value': '1', 'label': 'a'}, 2:{'value': '2', 'label': 'b'}]
but that gives me an error.
Right now I'm using unshift and it works, I wonder if there's a way to do the same with spread operator.
The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.
The fundamental idea of the object spread operator is to create a new plain object using the own properties of an existing object. So {... obj} creates a new object with the same properties and values as obj . For plain old JavaScript objects, you're essentially creating a copy of obj .
The push() method is used to add one or multiple elements to the end of an array. It returns the new length of the array formed. An object can be inserted by passing the object as a parameter to this method. The object is hence added to the end of the array.
I'm a little late but
You can solve this problem modifying it like this with spreed:
change:
var result = [newObj, ...oldArray]
for:
var result = [{...newObj}, ...oldArray]
You can use unshift()
to add items to the beginning of an array
var oldArray = [{'value': '1', 'label': 'a'}, {'value': '2', 'label': 'b'}]
var newObj = {'value': 'all', 'label': 'all'}
oldArray.unshift(newObj);
console.log(oldArray);
You could use the unshift()
function which does exactly that:
let oldArray = [{'value': '1', 'label': 'a'}, {'value': '2', 'label': 'b'}]
let newObj = {'value': 'all', 'label': 'all'}
oldArray.unshift(newObj)
console.log(oldArray)
Or if you don't want to modify the original array, you can do:
const result = oldArray.slice()
result.unshift(newObj)
console.log(result)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With