Search code examples
javascriptarraystypescriptmergejavascript-objects

type script merge objects left and right


how can I create a function to merge the two objects.

  1. First argument: Object to be merged (left)
  2. Second argument: Object to be merged (right)
  3. Third argument: Specify which property is left on the merged object. ('concat', 'left', 'right'), default is concat   

concat: Leave all properties of two objects    left: Property of returned object is property of object of first argument only    right: The property of the returned object is only the property of the object of the second argument

const input1 = {a: 'la', b: 'lb'};
const input2 = {a: 'ra', c: 'rc'};

// concat
mergeObj(input1, input2, 'concat'); // output: {a: 'ra', b: 'lb', c: 'rc'}
// left
mergeObj(input1, input2, 'left'); // output: {a: 'ra', b: 'lb'}
// right
mergeObj(input1, input2, 'right'); // output: {a: 'ra', c: 'rc'}


Solution

  • You can write a function mergeObj which based on the three conditions return the desired output

    First case- Concat: You need to merge two objects. You can simply use Object.assign to do that

    Second case- left: Map over the first object keys and if the value is present in second object set that else return the first object value itself.

    Third Case- right Simply return the second object

    const input1 = {a: 'la', b: 'lb'};
    const input2 = {a: 'ra', c: 'rc'};
    
    
    function mergeObj(inp1, inp2, type) {
    
      if(type === 'concat') {
        return Object.assign({}, inp1, inp2);
      } 
      if (type === 'left') {
         return Object.assign({}, ...Object.entries(inp1).map(([k, val]) => ({[k]: inp2[k] || val})));
      }
      if (type === 'right') {
        return Object.assign({}, inp2);
      }
    }
    // concat
    console.log(mergeObj(input1, input2, 'concat')); // output: {a: 'ra', b: 'lb', c: 'rc'}
    // left
    console.log(mergeObj(input1, input2, 'left')); // output: {a: 'ra', b: 'lb'}
    // right
    console.log(mergeObj(input1, input2, 'right')); // output: {a: 'ra', c: 'rc'}