0

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:..}]
3
  • 3
    unshift like push returns the length of the array after the item is added Commented Apr 30, 2020 at 8:13
  • @JaromandaX So how do I make it to return an object tho? Commented Apr 30, 2020 at 8:15
  • unshift adds whatever to the array and returns new length ... you can't change that Commented Apr 30, 2020 at 8:54

2 Answers 2

1

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];
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.