2017-09-22 49 views
2

我使用的數據集的字段爲continentcountry,city和`street。如你所想,每個領域取決於前一個領域。如何在值更改時清空對象的所有後續字段?

現在假定存在(部分)已完成的數據集,並且用戶更改country值。然後所有以下字段必須是空的。

這就是我如何做的(在我的情況下,數據是作爲一個狀態存儲在一個反應​​組件中 - 但這不應該在這裏)。 但對我來說,這看起來非常不活潑。我希望這可以做得更多'程序性'。

我的問題是,我不能只是迭代對象,因爲字段的順序不固定在一個js對象中。這將是一個陣列,但這裏並不是這樣...

if (data.name === 'continent') { 
    this.setState({ 
    continent: undefined, 
    country: undefined, 
    city: undefined, 
    street: undefined 
    }) 
} else if (data.name === 'country') { 
    this.setState({ 
    country: undefined, 
    city: undefined, 
    street: undefined 
    }) 
} else if (data.name === 'city') { 
    this.setState({ 
    city: undefined, 
    street: undefined 
    }) 
} else if (data.name === 'street') { 
    this.setState({ 
    street: undefined 
    }) 
} 

回答

1

由於字段確實具有層次結構和順序,因此可以將名稱存儲在數組中。然後取改變了現場和隨後的所有領域,並將其設置爲undefined,然後用Object.assign()來創建新的狀態,就像這樣:

var data = {name: "country"}; 
 
var fields = ["continent", "country", "city", "street"]; 
 
var state = { 
 
    continent: "North America", 
 
    country: "United States", 
 
    city: "Orlando", 
 
    street: "123 Main Street" 
 
} 
 
function clearFields (fieldName) { 
 
    var fieldIndex = fields.indexOf(fieldName); 
 
    var updatedState = {}; 
 
    if (~fieldIndex) { 
 
    updatedState = fields.slice(fieldIndex).reduce(function (newState, currField) { 
 
     newState[currField] = undefined; 
 
     return newState; 
 
    }, {}); 
 
    } 
 
    return Object.assign({}, state, updatedState); 
 
} 
 

 
console.log("Clear Continent..."); 
 
console.log(clearFields("continent")); 
 

 
console.log("Clear Country..."); 
 
console.log(clearFields("country")); 
 

 
console.log("Clear City..."); 
 
console.log(clearFields("city")); 
 

 
console.log("Clear Street..."); 
 
console.log(clearFields("street")); 
 

 
// to update react state... 
 
//this.setState(clearFields(data.name));

0

雖然對象字面順序是不確定的,數組排序不是。

所以,如果我們使用一個數組來找到開始定義的索引,我們就可以從那個索引繼續。

下面是一個例子。

let 
 
    seri = ['continent', 'country', 'city', 'street']; 
 
    
 
    
 
function clear(name, obj) { 
 
    let p = seri.indexOf(name); 
 
    for (let l = p; l < seri.length; l ++) 
 
    obj[seri[l]] = undefined; 
 
    return obj; 
 
} 
 

 
var 
 
    all = { 
 
    continent: 'continent', 
 
    country: 'country', 
 
    city: 'city', 
 
    street: 'street' 
 
    }; 
 

 
seri.forEach((c) => { 
 
    console.log(`clear ${c}`); 
 
    console.log(clear(c, Object.assign({},all))); 
 
});

1

你可以使用落空switch

switch(data.name) { 
    case 'continent': 
    this.setState({ continent: undefined }); 
    case 'country': 
    this.setState({ country: undefined }); 
    case 'city': 
    this.setState({ city: undefined }); 
    case 'street': 
    this.setState({ street: undefined }); 
} 
+0

但是,這將改變只有一個單一的價值......吧? – user3142695

+0

編號所有適用的。這是一個直通開關 – Amit

+1

可能更好,只需在對象上設置道具,然後在開關後設置一次狀態,而不是幾次 – mhodges

相關問題