简体   繁体   English

javascript:将 object 取消移位到 object 数组

[英]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.我有一个 object 需要插入到 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.我试过使用unshift ,我想要的是实现下面的结果,但它给了我数组的长度。

[{id:null, name: 'UNASSIGNED'},{id:.., name:..},{id:.., name:..},{id:.., name:..}]

Array#unshift mutates the array and returns the new length of the array. Array#unshift改变数组并返回数组的新长度。


For getting a new array, you could use Array#concat要获取新数组,您可以使用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. unshift()方法将一个或多个元素添加到数组的开头并返回数组的新长度。 But after using unshift() your original array api_data has been already updated.但是在使用unshift()之后,您的原始数组api_data已经更新。 Just use a console.log(api_data) on it to see the updated array with new static_stat object like:只需在其上使用console.log(api_data)即可查看带有新static_stat object 的更新数组,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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