undefinedfix
Sign in

JS two objects merge to get less attributes

JOSEPHJON edited in Thu, 28 Apr 2022

Let a = {A: 1, B: 4, C: 3}; want to get a = {A: 1, B: 4}; is there a one-step way? Like Object.assign A similar approach

3 Replies
joumak
commented on Fri, 29 Apr 2022
Object.keys(a).forEach((item,index)=>{
    a[item] = b[item]
})
jnewman
commented on Fri, 29 Apr 2022

I don't understand why in attribute a, one is empty, one is 1, and the last one is 1?

Do you mean this? For example, if there are multiple objects a, B and C, as long as one of them does not have this attribute, then the final object does not have this attribute?

For example:

let a = { a: '', b: '' },
b = { a: 1, b: 4, c: 3 };

There is no C attribute in object a, so there is no C attribute in the final data?

Nahuel
commented on Fri, 29 Apr 2022

You can use Es5 for reference Object.assign The method of treatment is as follows Object.assign

if (typeof Object.assignless != 'function') {
  // Must be writable: true, enumerable: false, configurable: true
  Object.defineProperty(Object, "assignless", {
    value: function assign(target, varArgs) { // .length of function is 2
      'use strict';
      if (target == null) { // TypeError if undefined or null
        throw new TypeError('Cannot convert undefined or null to object');
      }

      var to = new Object();

      for (var index = 1; index < arguments.length; index++) {
        var nextSource = arguments[index];

        if (nextSource != null) { // Skip over if undefined or null
          for (var nextKey in nextSource) {
            // Avoid bugs when hasOwnProperty is shadowed
            if (Object.prototype.hasOwnProperty.call(target, nextKey) && Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
              to[nextKey] = nextSource[nextKey];
            }
          }
        }
      }
      return to;
    },
    writable: true,
    configurable: true
  });
}

Since we only consider the minimum number of calls, we can just loop it once Object.assignless (a, b);

lock This question has been locked and the reply function has been disabled.