0

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

1 Answer 1

1

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

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

Comments

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.