![](/img/trans.png)
[英]How can I destructure a state array of objects in this react component to use individual field data
[英]how can I destructure from an array of objects when data is coming from database dynamically?
// foodItems is an array of object where one of it's key is id.
const [id1, id2, id3] = foodItems.map((item) => item.id);
// console.log(id1, id2, id3);
當數組為 static 通過執行上述代碼時,我可以通過解構來獲取 id。 但是,當數據來自該數組中的數據庫動態時,如何獲得相同的 id?
我真的不知道你的用例,但這通常看起來是個壞主意。 這是一個糟糕的模式,不要使用它,但無論如何它應該回答你的問題。 所以這里有一個例子:
['a', 'b', 'c'].forEach((data, i) => {
this[`id${i+1}`] = data
})
會導致這個:
id1: a
id2: b
id3: c
對於您的特定代碼,假設 object 有一個應該使用的“id”列(它仍然會在變量前面加上“id”):
foodItems.forEach((data) => {
this[`id${data.id}`] = data
})
假設 object 像const foodItems = [{id: 'foo', value: 'bar'}]
,它會導致:
idfoo: {id: 'foo', value: 'bar'}
如果您可以提供更多背景信息,也許我們可以提出一個更好的解決方案來真正幫助您?
async/await
)。map
在數據上獲取名稱數組(在本例中),或在您的情況下為 id。 // Returns the name from the current // iterated object function getName(data) { return data.name.first; } // Get the data, parse the data, map over the data async function getData(endpoint) { const res = await fetch(endpoint).catch(err => console.log(err)); const { results } = await res.json(); return results.map(getName); } // `await` `getData`, and destructure the things you want async function main(endpoint) { const [ fn1, fn2, fn3 ] = await getData(endpoint); console.log(fn1, fn2, fn3); } // Placeholder JSON resource const endpoint = 'https://randomuser.me/api/?results=3'; main(endpoint);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.