-1

I have an array of objects like this:

myArray = [
    {itemOneKey: 'itemOneValue', itemTwoKey: 'itemTwoValue'},
    {itemThreeKey: 'itemThreeValue'}
];

I wish to turn it to a single object like this:

myObject = {
    itemOneKey: 'itemOneValue',
    itemTwoKey: 'itemTwoValue',
    itemThreeKey: 'itemThreeValue'
}

in TypeScript. Anyone have a clue how I can go about to achieve this?

1
  • 1
    Note that if keys are repeated in the objects in your array (like if two objects have a property "itemKey"), then the result object will have only one value for that key. Commented Feb 22, 2023 at 20:02

1 Answer 1

4

You can use Object.assign with spread syntax to merge all the objects.

const myArray = [
    {itemOneKey: 'itemOneValue', itemTwoKey: 'itemTwoValue'},
    {itemThreeKey: 'itemThreeValue'}
];
const res = Object.assign({}, ...myArray);
console.log(res);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.