键入脚本左右合并对象

时间:2019-02-23 11:00:19

标签: javascript arrays typescript merge javascript-objects

我如何创建一个合并两个对象的函数。

  1. 第一个参数:要合并的对象(左)
  2. 第二个参数:要合并的对象(右)
  3. 第三个参数:指定在合并对象上保留哪个属性。 (“ concat”,“左”,“右”), 默认为concat

concat::保留两个对象的所有属性  左:返回的对象的属性仅是第一个参数的对象的属性  正确:返回的对象的属性仅是第二个参数的对象的属性

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'}

2 个答案:

答案 0 :(得分:2)

您可以简单地使用switch statementdestructuring assignment

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

const mergeObj = ( input1, input2, prop ) => {
  switch(prop){
    case 'left' : return {...input1};
    case 'right': return {...input2};
    default: return {...input1,...input2}
  }
}


console.log( mergeObj(input1, input2, 'concat') );
console.log( mergeObj(input1, input2, 'left') );
console.log( mergeObj(input1, input2, 'right') );

答案 1 :(得分:0)

您可以编写一个功能mergeObj,该函数基于这三个条件返回所需的输出

第一种情况-Concat :您需要合并两个对象。您只需使用Object.assign即可

第二种情况左:映射第一个对象键,如果该值存在于第二个对象集中,则返回第一个对象值本身。

第三种情况正确,只需返回第二个对象

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'}