繁体   English   中英

当数据动态来自数据库时,如何从对象数组中解构?

[英]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'}

如果您可以提供更多背景信息,也许我们可以提出一个更好的解决方案来真正帮助您?

  1. 从服务器获取响应(我在这个人为的示例中使用了async/await )。
  2. 将 JSON 解析为数据 object。
  3. map在数据上获取名称数组(在本例中),或在您的情况下为 id。
  4. 记录结果。

 // 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM