【问题标题】:type script merge objects left and right打字稿合并对象左右
【发布时间】:2019-07-17 08:39:49
【问题描述】:

如何创建一个函数来合并这两个对象。

  1. 第一个参数:要合并的对象(左)
  2. 第二个参数:要合并的对象(右)
  3. 第三个参数:指定合并对象上保留的属性。 ('连接','左','右'), 默认是连接

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

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

【问题讨论】:

  • 您的输出似乎与上述说法相矛盾

标签: javascript arrays typescript merge javascript-objects


【解决方案1】:

您可以简单地使用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') );

【讨论】:

  • 这也太棒了非常简短的答案,我还有两个问题我现在要发布,我想你可以帮助我!
  • 这并没有给出 OP 在他的 sn-p 的 cmets 中提到的输出
  • @ShubhamKhatri 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 我考虑了这些行并回答了。
  • 第一个对象的属性可能意味着只接受第一个对象的键并将值与第二个对象合并
【解决方案2】:

您可以编写一个函数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'}

【讨论】:

  • @d.Foo 你不认为你接受的答案没有给出你在问题中提到的输出。还是你问错了问题
  • @d.Foo 这不是你问的问题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 如果我理解错了请纠正我?
猜你喜欢
  • 1970-01-01
  • 2018-09-15
  • 2019-04-20
  • 2018-06-15
  • 1970-01-01
  • 1970-01-01
  • 2020-04-28
相关资源
最近更新 更多