如何在 TypeScript 中使用 Spread 运算符组合对象
How can I Combine using Spread Operator in TypeScript for an Object
我需要使用 Spread 运算符向对象添加值。但是当我使用它时,以前的值将从对象中删除。
我的对象是这样的
let newObj = {
name: 'sachin',
lastname: 'Tendulkar',
full_name: 'Sachin Ramesh Tendulkar',
test: {
test_debut: '15 November 1989 v Pakistan'
},
odi: {
odi_debut: '18 December 1989 v Pakistan'
},
t20: {
t20_debut: '1 December 2006 v South Africa'
}
}
我需要为此对象添加更多值
{
name: 'sachin',
lastname: 'Tendulkar',
full_name: 'Sachin Ramesh Tendulkar',
Born: '24 April 1973',
test: {
debut: '15 November 1989 v Pakistan',
last_match: '14 November 2013 v West Indies',
cap: 187
},
odi: {
debut: '18 December 1989 v Pakistan',
last_match: '18 March 2012 v Pakistan',
cap: 74
},
t20: {
debut: '1 December 2006 v South Africa',
last_match: '1 December 2006 v South Africa',
cap: 11
}
}
所以我添加了
const newValues = {
Born: '24 April 1973',
test: {
last_match: '14 November 2013 v West Indies',
cap: 187
},
odi: {
last_match: '18 March 2012 v Pakistan',
cap: 74
},
t20: {
last_match: '1 December 2006 v South Africa',
cap: 11
}
}
当我使用
newObj = {...newObj , ...newValues };
我得到的回复低于
{
name: 'sachin',
lastname: 'Tendulkar',
full_name: 'Sachin Ramesh Tendulkar',
Born: '24 April 1973',
test: {
last_match: '14 November 2013 v West Indies',
cap: 187
},
odi: {
last_match: '18 March 2012 v Pakistan',
cap: 74
},
t20: {
last_match: '1 December 2006 v South Africa',
cap: 11
}
}
如何在 typeScript 中解决这个问题
您需要单独 select 对象属性并单独展开其他对象 属性
const obj[key] = [...newObj[key], ...newValues[key]]
截至目前,它只是用新属性覆盖您的属性,因为它不会比较它覆盖的键
我需要使用 Spread 运算符向对象添加值。但是当我使用它时,以前的值将从对象中删除。
我的对象是这样的
let newObj = {
name: 'sachin',
lastname: 'Tendulkar',
full_name: 'Sachin Ramesh Tendulkar',
test: {
test_debut: '15 November 1989 v Pakistan'
},
odi: {
odi_debut: '18 December 1989 v Pakistan'
},
t20: {
t20_debut: '1 December 2006 v South Africa'
}
}
我需要为此对象添加更多值
{
name: 'sachin',
lastname: 'Tendulkar',
full_name: 'Sachin Ramesh Tendulkar',
Born: '24 April 1973',
test: {
debut: '15 November 1989 v Pakistan',
last_match: '14 November 2013 v West Indies',
cap: 187
},
odi: {
debut: '18 December 1989 v Pakistan',
last_match: '18 March 2012 v Pakistan',
cap: 74
},
t20: {
debut: '1 December 2006 v South Africa',
last_match: '1 December 2006 v South Africa',
cap: 11
}
}
所以我添加了
const newValues = {
Born: '24 April 1973',
test: {
last_match: '14 November 2013 v West Indies',
cap: 187
},
odi: {
last_match: '18 March 2012 v Pakistan',
cap: 74
},
t20: {
last_match: '1 December 2006 v South Africa',
cap: 11
}
}
当我使用
newObj = {...newObj , ...newValues };
我得到的回复低于
{
name: 'sachin',
lastname: 'Tendulkar',
full_name: 'Sachin Ramesh Tendulkar',
Born: '24 April 1973',
test: {
last_match: '14 November 2013 v West Indies',
cap: 187
},
odi: {
last_match: '18 March 2012 v Pakistan',
cap: 74
},
t20: {
last_match: '1 December 2006 v South Africa',
cap: 11
}
}
如何在 typeScript 中解决这个问题
您需要单独 select 对象属性并单独展开其他对象 属性
const obj[key] = [...newObj[key], ...newValues[key]]
截至目前,它只是用新属性覆盖您的属性,因为它不会比较它覆盖的键