let products = [ { name: "a", inventory: 1 }, { name: "b", inventory: 2 }, { name: "c", inventory: 3 } ];
How can I go about creating these objects in an array like this dynamically ? Here is what I have been trying to do.
choicesHolder = [{name: '', inventory: ''}]; for(i; element.length<0; i--) { choicesHolder.push({"name": element.value, "inventory": element.selected}); }
element holds the data from the JSON.
You can use the map method.
const choicesHolder = arrayOfElement.map(element => {
return {
name: element.value,
inventory: element.selected
}
})
Try this:
let res = []; let char = 'a' for (let i = 0; i < 4; i++) { res.push({ "name": char, "inventory": i + 1 }); char = String.fromCharCode(char.charCodeAt(0) + 1) // 'B' } console.log(res)
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.