1

i want to add an object into another object using typescript.

below is data1

data1 = {firstDetails: {...}}

data1 = {
            firstDetails: { 
                id: '1',
                name: 'first'
                description: 'description'
                //other fields,
            }
         } 

and there is data2 like below

 data2 {secondDetails: {...}}


const data2 = {
    secondDetails: {
        id: '1',
        items: [],
        values: [],

    }
}

now i want to remove property id from secondDetails and then take items and values from data2 and add it to data1.

so the expected output is like below

{ 
    firstDetails: {
        id: '1',
        name: 'first',
        description: 'description',
        items: [],
        values: [], 
    } 
}

i have tried like below,

const formattedData2 = formattedData2.secondDetails;
const without_id = omit(formattedData2, 'id')
data1.firstDetails = Object.assign(data1.firstDetails, without_id);

but this gives error in dat1.firstDetails in the last line. it says variable data has implicitly any type.

could someone help me fix this. how can i put one object into another using typescript. thanks.

0

3 Answers 3

5

Use destructuring with rest on second details. This way, you wont include the id from second

data1 = {
  firstDetails: {
    id: "1",
    name: "first",
    description: "description",
  },
};

const data2 = {
  secondDetails: {
    id: "2",
    items: [],
    values: [],
  },
};

const { id, ...restSecondDetails } = data2.secondDetails;

data1.firstDetails = { ...data1.firstDetails, ...restSecondDetails };

console.log(data1)

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

2 Comments

thanks but this doesnt put it in object firstDetails. pls look at the expected output in the question
@natalia, Check the updated answer.
2

Using spread and delete operator will help you here an example

delete formattedData2.secondDetails.id;
const object = {...data1.firstDetails, ...formattedData2.secondDetails}

If you want to push the property to the first object user;

Object.assign(data1.firstDetails, data2.secondDetails)

2 Comments

i want the firstDetails to be there still but add formattedData2.secondDetails into firstDetails object.
@Natalia check it out now.
-1

There's multiple ways to do this. I wouldn't use delete as this comes with unnecessary overhead.

A simple general way to do this would be as follows

const combinedObject = firstDetails
Object.keys(secondDetails).forEach(key => {
  if (key !== 'id') {
    combinedObject[key] = secondDetails[key]
  }
})

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.