简体   繁体   中英

javascript: unshift an object to an array of object

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:..}]

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];

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; }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM