1

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',
    },
];
2
  • I've tried different things - nothing works. What have you tried? array.unshift(myObj) works for me. Commented Aug 6, 2022 at 22:20
  • unshift doesn't create a new array, but modifies the main one Commented Aug 6, 2022 at 22:26

1 Answer 1

4

You can use the spread operator

const newArr = [newObj, ...array]

or

array.unshift(newObj)
Sign up to request clarification or add additional context in comments.

2 Comments

Invalid attempt to spread non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.
Try to destructure like this , const component = ({ array }) => { const newArr = [newObj, ...array] }

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.