Reputation: 47
I have a code that turns array into array objects
const thisArray = ['1', '2'];
Below is my function that converts it:
function macsFunction(codes){
const mappedObjects = codes.map(code => {
return {
'0': Number(code),
'1': 'Car'
};
});
return mappedObjects;
}
const thisSay = macsFunction(thisArray);
console.log(thisSay);
The result is like this:
[ { '0': 5, '1': 'Car' }, { '0': 13, '1': 'Car' } ]
Now it's been a long hours i wanted to achieve something like :
[null, { '0': 5, '1': 'Car' }, { '0': 13, '1': 'Car' } ]
I want to place a null
at the beginning of the array. But I've tried concat
, fill
, unshift
. It doesn't work. Happy to see if someone could help.
Upvotes: 0
Views: 114
Reputation: 96
You can use the unshift method to add something to the beginning of an array.
Documentation can be found here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift
Upvotes: 0
Reputation: 68933
You can use Array.prototype.unshift()
which adds one or more elements to the beginning of an array:
const thisArray = ['1', '2'];
function macsFunction(codes){
const mappedObjects = codes.map(code => {
return {
'0': Number(code),
'1': 'Car'
};
});
mappedObjects.unshift(null);
return mappedObjects;
}
const thisSay = macsFunction(thisArray);
console.log(thisSay);
Upvotes: 2