-1

I have two objects one is obj1 and obj2. I need to contact the obj2 in obj1 details array.

const obj1 = {
  name: 'test',
  phone: '233123',
  details: [{
      address1: 'test233',
      address2: 'testts'
    },
    {
      address1: 'test3',
      address2: 'testts'
    }
  ]
}

const obj2 = {
  address1: 'test4',
  address2: 'testts443'
}

obj1['details'].push(obj2);

console.log(obj1)

I tried with this code obj1['details'].push(obj2); when I tried to return the obj1 its return below output I tried in Object assign also it's not working for me.

my output

obj1 = {
        name:'test',
        phone:'233123'; 
        details: [
            {
                address1:'test233', 
                address2:'testts'
            }, 
            {
                address1:'test3', 
                address2:'testts'
            },
            [{
             address1:'test4', 
             address2:'testts443'
            }]
        ]
    }

my expected output is

obj1 = {
            name:'test',
            phone:'233123'; 
            details: [
                {
                    address1:'test233', 
                    address2:'testts'
                }, 
                {
                    address1:'test3', 
                    address2:'testts'
                },
                {
                 address1:'test4', 
                 address2:'testts443'
                }
            ]
        }
techie18
  • 774
  • 1
  • 7
  • 19
  • 1
    I'm intrigued because your `obj1['details'].push(obj2);` and the suggested `obj1.details.push(obj2);` are essentially the same...Might it be something related to the semicolon you have after the `phone` value? Is something changing if you substitute it with a comma? – malarres Jun 22 '20 at 14:22

2 Answers2

0

A simple push my friend,

obj1.details.push(obj2)

Bar Levin
  • 218
  • 1
  • 10
0

From your second example it looks like the obj2 is an array. If this is the case, you can use concat function to merge the two arrays.

obj1.details = obj1.details.concat(obj2);
AC101
  • 681
  • 6
  • 11