[英]How do I loop through a JSON array of objects in javascript?
I want to loop through the JSON file - I believe it is an array of objects.我想遍历 JSON 文件 - 我相信它是一个对象数组。 For each object, I want to get the 'name' property as well as the name of each ingredient and its value (in string form) to display in it's own div.
对于每个 object,我想获取“名称”属性以及每种成分的名称及其值(以字符串形式)以显示在它自己的 div 中。 JSON file and JS code follow.
JSON 文件和 JS 代码如下。 No matter what I do I cannot seem to loop and access the properties successfully.
无论我做什么,我似乎都无法成功循环和访问属性。
JSON JSON
[{ "name": "Rum & Coke", "ingredients": { "rum": 50, "coke": 150 } }, { "name": "Gin & Tonic", "ingredients": { "gin": 50, "tonic": 150 } }, { "name": "Long Island", "ingredients": { "gin": 15, "rum": 15, "vodka": 15, "tequila": 15, "coke": 100, "oj": 30 } }, { "name": "Screwdriver", "ingredients": { "vodka": 50, "oj": 150 } } ]
const data = require('./drinkList.json') const data = JSON.parse(data) var mainContainer = document.getElementById("drinks"); for (let i in data) { var div = document.createElement("div"); div.setAttribute("class", "DrinkContainer") var drinkName = document.createElement("p") drinkName.setAttribute("class", "DrinkName") drinkName.innerHTML = data[i]['name'] div.appendChild(drinkName); var drinkIngredients = document.createElement("p") drinkIngredients.setAttribute("class", "DrinkIngs") const ingredientsInDrink = data[i]['ingredients'] let ingNameArray = Object.keys(ingredientsInDrink) for (const x in ingNameArray) { for (const amount in ingredientsInDrink[x]) { const ing = x; const ingAmount = amount.toString(); const stringForIngredients = ingAmount + "mls of " + ing } } drinkIngredients.innerHTML = stringForIngredients div.appendChild(drinkIngredients) mainContainer.append(div) }
I've changed your code a little but kept it mostly consistent with what you were trying to achieve.我对您的代码进行了一些更改,但使其与您想要实现的目标基本一致。
const data=[{name:'Rum & Coke',ingredients:{rum:50,coke:150}},{name:'Gin & Tonic',ingredients:{gin:50,tonic:150}},{name:'Long Island',ingredients:{gin:15,rum:15,vodka:15,tequila:15,coke:100,oj:30}},{name:'Screwdriver',ingredients:{vodka:50,oj:150}}]; const mainContainer = document.getElementById('drinks'); // For arrays you should be using for...of for (let obj of data) { const div = document.createElement('div'); div.setAttribute('class', 'drinkContainer') const drinkName = document.createElement('p') drinkName.setAttribute('class', 'drinkName') // We can now use obj.name rather than data[i]['name'] drinkName.innerHTML = obj.name; div.appendChild(drinkName); const drinkIngredients = document.createElement('p'); drinkIngredients.setAttribute('class', 'DrinkIngs'); const entries = Object.entries(obj.ingredients); // Instead of a string create a new element const ingredients = document.createElement('div'); // Instead of Object.keys use Object.entries which // returns an array of a key/value pair which I've // named `name` and `amount` for (const [name, amount] of entries) { // Create a new paragraph element const ingredient = document.createElement('p'); // Update the text content of the paragraph ingredient.textContent = amount + 'mls of ' + name; // And append it to the ingredients div ingredients.appendChild(ingredient); } div.appendChild(ingredients); mainContainer.append(div); }
.drinkContainer { background-color: #efefef; padding: 1em; margin: 1em; }.drinkName { font-weight: 700; }
<div id="drinks"></div>
A more modern approach might be to use template strings and map
to build up HTML, and then add the final result as the innerHTML of a DOM element.更现代的方法可能是使用模板字符串和
map
来构建 HTML,然后将最终结果添加为 DOM 元素的 innerHTML。
const data=[{name:"Rum & Coke",ingredients:{rum:50,coke:150}},{name:"Gin & Tonic",ingredients:{gin:50,tonic:150}},{name:"Long Island",ingredients:{gin:15,rum:15,vodka:15,tequila:15,coke:100,oj:30}},{name:"Screwdriver",ingredients:{vodka:50,oj:150}}]; // `map` over the data array const html = data.map(obj => { // Destructure the name and ingredient props const { name, ingredients } = obj; // Create some HTML for the name. We're using // template strings for ease of reading const nHtml = `<p class="name">${name}</p>`; // Get the object entries of the ingredient object const iEntries = Object.entries(ingredients); // `map` over the entries and create some HTML // for the ingredient name and value. `map` returns // and array so we need to `join` it into a string const iHtml = iEntries.map(([name, value]) => { return `<p>${name} - ${value}`; }).join(''); // Return the combined HTML for the name and ingredients return `<div class="drink"><p>${nHtml}</p>${iHtml}</div>`; }).join(''); // Add the HTML to the DOM element document.querySelector('#main').innerHTML = html;
.name { font-weight: 700; }.drink { background-color: #efefef; padding: 1em; margin: 1em; }
<div id="main"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.