Home > Back-end >  How to add another object to an object using typescript?
How to add another object to an object using typescript?

Time:05-04

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.

CodePudding user response:

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)

CodePudding user response:

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)

CodePudding user response:

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]
  }
})
  • Related