Monday 15 July 2019

javascript - Add object to the beginning of array using spread operator

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.

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...