0

I wanted to merge nested javascript object. I was simple when I the length of object was one. But since the lenght has increased I need a dynamic way to merge the address key and serialize my object

var old =  {account: "100000", address: {city: "LONDON", companyName: "Test IQUE", country: "UK", postalCode: "SW1A 2AA",}, meterName: "DM9"}

When lenght was 1 this worked for me

var new = {   
              'account' : "100000",                         
              'address' : "LONDON, UK"
              'companyName' : "Test IQUE",
              'postalCode' : "SW1A 2AA",   
              'meterName' : "DM90"
           },
           {   
              'account' : "1000001",                         
              'address' : "LONDON, UK"
              'companyName' : "Test IQUE",
              'postalCode' : "SW1A 2AA",   
              'meterName' : "DM90"
           };

Baiscally I need to serialize my nested address object and merge it into one. As the structure of each object will be same I was thinking of using a for each loop which can combine values of address into one.

Duck_dragon
  • 440
  • 5
  • 17

2 Answers2

0

If you're asking how you can get a full address string from an addresss object, you can use the following code:

'address': Object.values($scope.userDetails.address).join(', ');

The Object.values() function will change your address object into array.

The .join method will concatenate all of the elements from this array into one string. These elements will be separated by a string passed as an argument (, in this case).

Przemysław Niemiec
  • 1,704
  • 1
  • 11
  • 14
0

You can use lodash lib : https://lodash.com/docs/4.17.15#assignIn

@see

_.assign(object, [sources])

function Foo() {
    this.a = 1;
}

function Bar() {
    this.c = 3;
}

Foo.prototype.b = 2;
Bar.prototype.d = 4;

_.assign({ 'a': 0 }, new Foo, new Bar);
// => { 'a': 1, 'c': 3 }

_.mergeWith(object, other, customizer);

function customizer(objValue, srcValue) {
    if (_.isArray(objValue)) {
        return objValue.concat(srcValue);
    }
}
 
var object = { 'a': [1], 'b': [2] };
var other = { 'a': [3], 'b': [4] };
 
_.mergeWith(object, other, customizer);
// => { 'a': [1, 3], 'b': [2, 4] }
Adrien Parrochia
  • 785
  • 8
  • 10