Reputation: 45
I have an object that i need to insert in the front(first index) of an array of object.
const static_stat = {id: null, name: 'UNASSIGNED'};
api_data = [{id:.., name:..},{id:.., name:..},{id:.., name:..}];
I've tried using unshift
, What I want is to achieve the result below, but it gives me the length of the array instead.
[{id:null, name: 'UNASSIGNED'},{id:.., name:..},{id:.., name:..},{id:.., name:..}]
Upvotes: 0
Views: 6398
Reputation: 73936
Yes, you are right. The unshift()
method adds one or more elements to the beginning of an array and returns the new length of the array. But after using unshift()
your original array api_data
has been already updated. Just use a console.log(api_data)
on it to see the updated array with new static_stat
object like:
const static_stat = {id: null, name: 'UNASSIGNED'};
let api_data = [{id: 1, name: 'Jhon'}];
console.log(api_data.unshift(static_stat));
console.log(api_data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1
Reputation: 386746
Array#unshift
mutates the array and returns the new length of the array.
For getting a new array, you could use Array#concat
return [static_stat].concat(api_data);
or take a new array with spreaded items.
return [static_stat, ...api_data];
Upvotes: 1