[英]Remove an key value from an object in react js
我在該州有一個對象,
this.state = {
selectedValue: {}
}
現在,我在這里通過以下方式向對象添加屬性
if (e.currentTarget.checked) {
this.setState({
selectedType: {
...this.state.selectedType,
[resumeId]: type
}
})
現在,在其他部分我必須使用匹配的resumeId
刪除該屬性。
或者我需要創建一個array of objects
嗎? 我有點困惑。
誰能幫我這個 ?
最好的方法是在resumId
添加一個前綴:
if (e.currentTarget.checked) {
this.setState({
selectedType: {
...this.state.selectedType,
[`resume-${resumeId}`]: type
}
})
現在,您有辦法識別您的resumeId。 然后遍歷您的selectedType
狀態並刪除resumeId
。 您可以按以下方式執行此操作:
let selectedType = this.state.selectedType;
for (let key in selectedType) {
if (key.indexOf('resume') !== -1) {
delete selectedType[key]
}
}
this.setState({selectedType})
if (e.currentTarget.checked) { this.setState({ selectedType: { ...this.state.selectedType, [resumeId]: type } }) else { const selectedType = { ...this.state.selectedType } delete selectedType[resumeId]; this.setState({ selectedType }); }
您可以從對象iself中刪除resumeId。
使用Object destructuring
來干凈利落地實現:
if (e.currentTarget.checked) {
this.setState({
selectedType: {
...this.state.selectedType,
[resumeId]: type
}
})
} else {
// Destructure the resumeId and rest properties
const { resumeId, ...rest} = this.setState.selectedType;
// Only assign the rest properties now
this.setState({ selectedType: ...rest });
}
更新:
要檢查所有值是否相同:
const data = { "a": "11", "b": "11", "c":"12", "d" : "11" }; const objectValues = Object.values(data); // Check first value with every value const isEveryValueSame = objectValues.every(x => x === objectValues[0]); console.log(isEveryValueSame);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.