简体   繁体   中英

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. But, How can I get the same id's when the data is coming from database dynamically in this array?

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"):

foodItems.forEach((data) => {
  this[`id${data.id}`] = data
})

Assuming an object like const foodItems = [{id: 'foo', value: 'bar'}] , it would result in this:

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?

  1. Get the response from the server (I've used async/await in this contrived example).
  2. Parse the JSON to a data object.
  3. map over the data to get an array of names (in this example), or ids in your case.
  4. Log the results.

 // 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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