sarpay
11/13/2018 - 8:10 AM

Objects

Declare, Assign, Iterate

// construct, inline assign
Object.assign({
  background: 'var(--info)',
  imageClass: 'fa fa-info-circle'
}, options)
        
// declaration
var car = {};
car.brand = 'Alfa Romeo';
car.make = '156';
car.year = 2005;
car.details = [];
car.details.push({
  max_speed: '200 KM',
  one_to_sixty: '10 sec.',
  cylinders: 4,
  rear_wheel: false
});
// -- or -- //
var person = {
    firstName:"John",
    lastName:"Doe",
    age:50,
    eyeColor:"blue"
};
// -- or -- //
var person = new Object();
var key = 'firstName';
person[key] = 'John';

// accessing its values
console.log(person.lastName);
console.log(person["lastName"]);

// loop through items
var data = {};
data.items = [];
data.items.push({ID: 1, DeckType: 'W', ModelName: 'OPS-MT-0100', PipeRange: '1/2 to 1', DimCenter: '2.9250'});
data.items.push({ID: 2, DeckType: 'W', ModelName: 'OPS-MT-0100-C', PipeRange: '1/2 to 2', DimCenter: '1.6750'});
data.items.push({ID: 3, DeckType: 'C', ModelName: 'CD-0200', PipeRange: '1/4 to 1-1/4', DimCenter: '2.1600'});
var getThis = false;
/*** (ix) gives the index, (obj) gives the object in turn ***/
$.each(data.items, function (ix, obj) { /*** iterates rows ***/
  getThis = false;
  $.each(obj, function (key, value) { /*** iterates columns of each row ***/
    if (key == 'DeckType' && value == 'W') { getThis = true; }
  });
  if (getThis) {
    $('#selectbox').append($('<option>', obj.ID).text(obj.ModelName));
  }
});

What is the object type?

if (typeof checkedVal != 'undefined') {}
if (typeof maxRecords === 'number') {}
if (typeof firstName === 'string') {}
if (typeof optIn === 'boolean') {}

Extraction (ES2018 final draft)

We can now extract Object properties using the rest parameter ...
So in this example, we are extracting coffee and origin,
while storing the rest inside leftover:

let {coffee, origin, ... leftover} = {
  coffee: ‘40 sardines blend’,
  origin: ‘guatemala’,
  roast: ‘italian’,
  price: ‘12.64’
};
coffee; // “40 sardines blend”
origin; // “guatemala”
leftover; // {roast: “italian”, price: “12.64”}

Copying

-- https://smalldata.tech/blog/2018/11/01/copying-objects-in-javascript#sidebar

In this article we will look at the various ways an object can be copied in Javascript. We will take a look at both shallow and deep copying.

Before we begin, it is worth mentioning a few basics: objects in Javascript are simply references to a location in memory. These references are mutable, i.e. they can be reassigned. Thus, simply making a copy of a reference only results in 2 references pointing to the same location in memory:

var foo =  { 
    a :  "abc"  
};
console.log(foo.a);  // abc

var bar = foo;
console.log(bar.a);  // abc

foo.a =  "yo foo";
console.log(foo.a);  // yo foo
console.log(bar.a);  // yo foo

bar.a =  "whatup bar?";
console.log(foo.a);  // whatup bar?
console.log(bar.a);  // whatup bar?

As you see in the above example, both foo and bar are reflecting the change done in either object. Thus, making a copy of an object in Javascript requires some care depending upon your use case.

Merge

Merge objects with same props like this;

var combinedOptions = Object.assign({}, defaultOptions, options);

Shallow copy

If your project has lodash:

const inputDtoClone = _.clone(this.inputDto);

If your object only has properties which are value types, you can use the spread syntax or Object.assign(...)

var obj =  { foo:  "foo", bar:  "bar"  };
var copy =  {  ...obj };  // Object { foo: "foo", bar: "bar" }
var obj =  { foo:  "foo", bar:  "bar"  };
var copy =  Object.assign({}, obj);  // Object { foo: "foo", bar: "bar" }

Note that both of the above methods can be used to copy property values from multiple source objects to a target object:

var obj1 =  { foo:  "foo"  };
var obj2 =  { bar:  "bar"  };
var copySpread =  {  ...obj1,  ...obj2 };  // Object { foo: "foo", bar: "bar" }
var copyAssign =  Object.assign({}, obj1, obj2);  // Object { foo: "foo", bar: "bar" }

The problem with the above methods lies in the fact that for objects with properties which are themselves objects, only the references are copied over, i.e. it is the equivalent of doing var bar = foo; as in the first code example:

var foo =  { a: 0, b: { c:  0 } };
var copy = { ...foo };

copy.a = 1;
copy.b.c = 2;

console.dir(foo);  // { a: 0, b: { c: 2 } }
console.dir(copy);  // { a: 1, b: { c: 2 } }

Deep copy (with caveats)

In order to deep copy objects, a potential solution can be to serialize the object to a string and then deserialize it back:

var obj = { a: 0, b: { c: 0 } };
var copy = JSON.parse(JSON.stringify(obj));

Unfortunately, this method only works when the source object contains serializable value types and does not have any circular references. An example of a non-serializable value type is the Date object - it is printed in a non ISO-standard format and cannot be parsed back to its original value :(.

Conclusion

To sum up, the best algorithm for copying objects in Javascript is heavily dependent on the context and type of objects that you are looking to copy. While lodash is the safest bet for a generic deep copy function, you might get a more efficient implementation if you roll your own, the following is an example of a simple deep clone that works for dates as well:

function deepClone(obj) {
  var copy;

  // Handle the 3 simple types, and null or undefined
  if (null == obj || "object" != typeof obj) return obj;

  // Handle Date
  if (obj instanceof Date) {
    copy = new Date();
    copy.setTime(obj.getTime());
    return copy;
  }

  // Handle Array
  if (obj instanceof Array) {
    copy = [];
    for (var i = 0, len = obj.length; i < len; i++) {
        copy[i] = clone(obj[i]);
    }
    return copy;
  }

  // Handle Function
  if (obj instanceof Function) {
    copy = function() {
      return obj.apply(this, arguments);
    }
    return copy;
  }

  // Handle Object
  if (obj instanceof Object) {
      copy = {};
      for (var attr in obj) {
          if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
      }
      return copy;
  }

  throw new Error("Unable to copy obj as type isn't supported " + obj.constructor.name);
}