Answers for "javascript merge objects"

14

clone object in js

var student = {name: "Rahul", age: "16", hobby: "football"};

//using ES6
var studentCopy1 = Object.assign({}, student);
//using spread syntax
var studentCopy2 = {...student}; 
//Fast cloning with data loss
var studentCopy3 = JSON.parse(JSON.stringify(student));
Posted by: Guest on April-29-2020
43

merge two objects javascript

const object1 = {
  name: 'Flavio'
}

const object2 = {
  age: 35
}
const object3 = {...object1, ...object2 } //{name: "Flavio", age: 35}
Posted by: Guest on July-13-2020
5

javascript merge objects

var person={"name":"Billy","age":34};
var clothing={"shoes":"nike","shirt":"long sleeve"};

var personWithClothes= Object.assign(person, clothing);//merge the two object
Posted by: Guest on July-22-2019
8

merge objects javascript

const a = { b: 1, c: 2 };
const d = { e: 1, f: 2 };

const ad = { ...a, ...d }; // { b: 1, c: 2, e: 1, f: 2 }
Posted by: Guest on March-03-2020
0

javascript merge objects

// reusable function to merge two or more objects
function mergeObj(...arr){
  return arr.reduce((acc, val) => {    
    return { ...acc, ...val  };
  }, {});
}

// test below

const human = { name: "John", age: 37 };

const traits = { age: 29, hobby: "Programming computers" };

const attribute = { age: 40, nationality: "Belgian" };

const person = mergeObj(human, traits, attribute);
console.log(person);
// { name: "John", age: 40, hobby: "Programming computers", nationality: "Belgian" }
Posted by: Guest on March-02-2021
0

javascript merge objects

/**
 * Simple object check.
 * @param item
 * @returns {boolean}
 */
export function isObject(item) {
  return (item && typeof item === 'object' && !Array.isArray(item));
}

/**
 * Deep merge two objects.
 * @param target
 * @param ...sources
 */
export function mergeDeep(target, ...sources) {
  if (!sources.length) return target;
  const source = sources.shift();

  if (isObject(target) && isObject(source)) {
    for (const key in source) {
      if (isObject(source[key])) {
        if (!target[key]) Object.assign(target, { [key]: {} });
        mergeDeep(target[key], source[key]);
      } else {
        Object.assign(target, { [key]: source[key] });
      }
    }
  }

  return mergeDeep(target, ...sources);
}
Posted by: Guest on August-03-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language