gpt4 book ai didi

javascript - typescript 左右合并对象

转载 作者:行者123 更新时间:2023-12-01 01:15:04 25 4
gpt4 key购买 nike

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

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

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

最佳答案

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

关于javascript - typescript 左右合并对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54840859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com