Reputation: 43
I have an array of objects (this array comes as a prop from the parent component) and the object. I have to add the object at the begging of my array. I've tried different things - nothing works.
const array = [
{
key1: 'a',
key2: 'b',
key3: 'c',
},
{
key1: 'd',
key2: 'e',
key3: 'f',
},
];
const myObj = {
key1: '1',
key2: '2',
key3: '3',
};
The result I want to see:
const myArray = [
{
key1: '1',
key2: '2',
key3: '3',
},
{
key1: 'a',
key2: 'b',
key3: 'c',
},
{
key1: 'd',
key2: 'e',
key3: 'f',
},
];
Upvotes: 1
Views: 813
Reputation:
You can use the spread
operator
const newArr = [newObj, ...array]
or
array.unshift(newObj)
Upvotes: 4