简体   繁体   English

如何循环通过 javascript 中的对象的 JSON 数组?

[英]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.

相关问题 如何遍历 Javascript 中的 JSON 对象数组? - How do I iterate through an array of JSON objects in Javascript? 如何循环遍历 json 数组项并使用某些 json 对象发出异步 API 请求 - How do I loop through an array item of json and make async API requests with certain json objects 在Javascript中循环对象的JSON数组 - Loop through JSON array of objects in Javascript 如何遍历一个复杂的JSON对象数组,其中包含数组和动态键? - How do I loop through a complicated array of JSON objects with arrays inside it and dynamic keys? 如何遍历对象数组中的数组 - How do I loop through an array in an array of objects 如何使用forEach遍历Javascript数组对象以创建元素? - How do I loop through Javascript array objects with forEach to create an element? Javascript对象数组 - 如何循环并获取对象值 - Javascript Array of objects - how do i loop through and get the object values 如何在具有多个对象的数组中循环并仅使用Javascript列出某些元素? - How do I loop through an array with multiple objects and list certain elements in solely Javascript? 如何遍历 javascript 中的这个对象数组? - How can I loop through this array of objects in javascript? 如何循环对象并按Javascript中的时间戳进行分类? - How do I loop through objects and categorize by timestamps in Javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM