簡體   English   中英

如何從 object 數組中的 object 獲取數據

[英]How to get data from object in an array of object

我有以下 object:

const fruit = { type: [apple, orange, grape, kiwi], amount: [apple, orange, apple, grape];

這意味着有4種水果,分別是蘋果、橙子、葡萄和獼猴桃,其中有2個蘋果、1個橙子和1個葡萄。

如何使用 for 循環打印如下內容:蘋果:2 橙:1 葡萄:1 獼猴桃:0

試試下面的代碼。

 // Your Input const fruit = { type: ['apple', 'orange', 'grape', 'kiwi'], amount: ['apple', 'orange', 'apple', 'grape'], }; // Counting array items and store as an object const fruitCount = fruit.amount.reduce( (acc, item) => ({...acc, [item]: (acc[item]?? 0) + 1, }), {} ); // Printing items according to type from input fruit.type.map(e => { console.log(e, fruitCount[e] || 0) })

嘗試以下代碼以獲取 output

 const fruits = {type: ["apple", "orange", "grape", "kiwi"], amount: ["apple", "orange", "apple", "grape"],}; const fruitsMap = new Map(); Object.keys(fruits).forEach((key) => { fruits[key].forEach((fruit) => { if (fruitsMap.has(fruit)) { fruitsMap.set(fruit, fruitsMap.get(fruit) + 1); } else { fruitsMap.set(fruit, 1); } }); }); let fruitsStr = ""; for (const [key, value] of fruitsMap.entries()) { fruitsStr += `${key}: ${value} `; } console.log(fruitsStr);

 const fruit = { type: ['apple', 'orange', 'grape', 'kiwi'], amount: ['apple', 'orange', 'apple', 'grape']}; let types = {}; fruit.type.forEach(elem=>{ //making a js object of fruit types types[elem] = elem; }); let amounts = fruit.amount; let result={}; Object.keys(types).forEach(type=>{ //reset the amounts per fruit. result[type] = 0; }) amounts.forEach(fruit=>{ //every accurance of a fruit, plus one to the value. result[fruit]++; }); console.log(result)

試試下面的代碼。 第一個 output 是 object。 其他的是字符串。

 // Input const fruit = { type: ['apple', 'orange', 'grape', 'kiwi'], amount: ['apple', 'orange', 'apple', 'grape'], }; // Create an Object to store fruit information const fruitInfo = new Object() fruit.type.forEach(item => fruitInfo[item] = 0); // Output: {apple: 0, grape: 0, kiwi: 0, orange: 0} // Count fruit Object.keys(fruitInfo).forEach(key => { fruit.amount.forEach(item => { if (item == key) { fruitInfo[key]++; } }) }); console.log(fruitInfo); // Log raw data (an object) // ------ APPENDIX ------- // Log fruit one by one (strings) Object.keys(fruitInfo).forEach(key => console.log(`${key}: ${fruitInfo[key]}`));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM