[英]best way to search and delete with given values, for delete from array inside the object and return new array of object javascript?
[英]Return object with default values from array in Javascript
const fields = ['email', 'password'];
const objFields = {};
fields.forEach(value => {
objFields[value] = '';
});
console.log(objFields);
// Outputs {email: "", password: ""}
我想獲得相同的結果,但不必初始化一個空對象。
實際上我的情況是我想設置 React 組件的初始狀態。
class App extends Component {
fields = ['email', 'password'];
state = {
fields: // the one liner code here that should return the object created from fields array,
};
...
預期結果是
// state = {fields: {email: "", password: ""}}
每當您想將一組值減少到一個值時,您都在尋找.reduce()
state = {
fields: fields.reduce((acc, key) => ({...acc, [key]: ''}), {}),
};
您可以映射對象並將所有對象分配給單個對象。
const fields = ['email', 'password'], object = Object.assign({}, ...fields.map(key => ({ [key]: '' }))); console.log(object);
您需要將包含鍵的數組轉換為真實對象。
要做到這一點,您有很多可能性,但您仍然必須做一些事情,沒有什么神奇的技巧。
我最喜歡的方法是使用一個函數插入到您的 Utilitary 類中。 所以它很容易閱讀和重復使用。
function initializeKeys(keys, initialValue, object) { return keys.reduce((tmp, x) => { tmp[x] = initialValue; return tmp; }, object); } const objFields = initializeKeys(['email', 'password'], '', { otherKey: 'a', }); console.log(objFields);
const fields = ['email', 'password']; const objFields = {}; fields.forEach(value => { objFields[value] = ''; }); console.log(objFields);
const fields = ['email', 'password']; const objFields = { ...fields.reduce((tmp, x) => { tmp[x] = ''; return tmp; }, {}), }; console.log(objFields);
在現代瀏覽器中,或者通過使用 polyfills ,您可以使用Object.fromEntries()
從數組創建對象,使用數組的值作為鍵/屬性,並使用默認值填充對象的值。
const fields = ['email', 'password'];
const result = Object.fromEntries(fields.map(value => [value, '']));
結果是{email: "", password: ""}
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.