Renjith Krishnan
Renjith Krishnan

Reputation: 2616

How can I Combine using Spread Operator in TypeScript for an Object

I need to add values to a object using the Spread operator. But when I use it the previous values getting removed from the object.

My object is like

let newObj = {
name: 'sachin',
lastname: 'Tendulkar',
full_name: 'Sachin Ramesh Tendulkar',
test: {
  test_debut: '15 November 1989 v Pakistan'
},
odi: {
  odi_debut: '18 December 1989 v Pakistan'
},
t20: {
  t20_debut: '1 December 2006 v South Africa'
}
}

to this object I need to add Some more values

{
    name: 'sachin',
    lastname: 'Tendulkar',
    full_name: 'Sachin Ramesh Tendulkar',
    Born: '24 April 1973',
    test: {
        debut: '15 November 1989 v Pakistan',
        last_match: '14 November 2013 v West Indies',
        cap: 187
    },
    odi: {
        debut: '18 December 1989 v Pakistan',
        last_match: '18 March 2012 v Pakistan',
        cap: 74
    },
    t20: {
        debut: '1 December 2006 v South Africa',
        last_match: '1 December 2006 v South Africa',
        cap: 11
    }
}

so for that I added

const newValues = {
  Born: '24 April 1973',
  test: {
            last_match: '14 November 2013 v West Indies',
            cap: 187
        },
   odi: {
            last_match: '18 March 2012 v Pakistan',
            cap: 74
        },
   t20: {
            last_match: '1 December 2006 v South Africa',
            cap: 11
        }
}

When I use

newObj = {...newObj , ...newValues };

I got below response

{
    name: 'sachin',
    lastname: 'Tendulkar',
    full_name: 'Sachin Ramesh Tendulkar',
    Born: '24 April 1973',
    test: {
        last_match: '14 November 2013 v West Indies',
        cap: 187
    },
    odi: {
        last_match: '18 March 2012 v Pakistan',
        cap: 74
    },
    t20: {
        last_match: '1 December 2006 v South Africa',
        cap: 11
    }
}

How can I fix this in typeScript

Upvotes: 0

Views: 99

Answers (1)

voiys
voiys

Reputation: 299

You would need to select the objects properties individually and spread the other objects property individually as well

const obj[key] = [...newObj[key], ...newValues[key]]

As of right now it just overwrites your properties with new ones because it doesnt compare the keys it overwrites

Upvotes: 1

Related Questions