简体   繁体   中英

Create Variables based on data from an array.

I'd like to use data from an object to ultimately assign variables based on that string to create a getElementById selector that's also based on that string.

I'm hoping to use array destructuring to create a variables based on the items in arr with the returned items in mappedArr, but if there's a much easier way, please chime in.

I have an array of objects.

I create an array called arr.

I take the array called dataSample and map over it. When I map over it, I push element.divId into arr

I also return a template literal that fills out the right hand side of an assignment for a document.getElementById selection.

   
   

 var dataSample = [ { "sampleItem": "sampleItem", "divId": "first" }, { "sampleItem": "sampleItem", "divId": "second" } ] var arr = []; var mappedArr = dataSample.map( function(element) { arr.push(element.divId); return `document.getElementById("${element.divId}")` } ); // I would like to dynamically assign variables like... // var first = document.getElementById("first"); // var second = document.getElementById("second"); // Etc., Etc. 
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <div id="first">hey</div> <div id="second">hey</div> <div id="third">hey</div> </body> </html> 

First .map the dataSample array to each item's associated HTMLElement by using getElementById , and then you can destructure on the left-hand side immediately, only one line required:

 var dataSample = [ { "sampleItem": "sampleItem", "divId": "first" }, { "sampleItem": "sampleItem", "divId": "second" } ] const [first, second] = dataSample.map(({ divId }) => document.getElementById(divId)); console.log(first.id); console.log(second.id); 
 <div id="first">hey</div> <div id="second">hey</div> <div id="third">hey</div> 

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