[英]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);
I can get id's by destructuring when array is static by doing above's code.当数组为 static 通过执行上述代码时,我可以通过解构来获取 id。 But, How can I get the same id's when the data is coming from database dynamically in this array?
但是,当数据来自该数组中的数据库动态时,如何获得相同的 id?
I don't really know you use-case for this but it generally seems like a bad idea.我真的不知道你的用例,但这通常看起来是个坏主意。 This is a poor pattern, do not use it, but it should answer your question anyways.
这是一个糟糕的模式,不要使用它,但无论如何它应该回答你的问题。 So here is an example:
所以这里有一个例子:
['a', 'b', 'c'].forEach((data, i) => {
this[`id${i+1}`] = data
})
Would lead to this:会导致这个:
id1: a
id2: b
id3: c
For your specific code, assuming the object has an "id" column that should be used (which would still prefix the variable with "id"):对于您的特定代码,假设 object 有一个应该使用的“id”列(它仍然会在变量前面加上“id”):
foodItems.forEach((data) => {
this[`id${data.id}`] = data
})
Assuming an object like const foodItems = [{id: 'foo', value: 'bar'}]
, it would result in this:假设 object 像
const foodItems = [{id: 'foo', value: 'bar'}]
,它会导致:
idfoo: {id: 'foo', value: 'bar'}
If you can provide some more context, maybe we could come up with a better solution that actually helps you?如果您可以提供更多背景信息,也许我们可以提出一个更好的解决方案来真正帮助您?
async/await
in this contrived example).async/await
)。map
over the data to get an array of names (in this example), or ids in your case. 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.