简体   繁体   English

如何从 object 数组中的 object 获取数据

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

I have an object of the following:我有以下 object:

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

it means that there is 4 types of fruit which is apple, orange, grape, and kiwi and there are 2 apples, 1 orange, and 1 grape.这意味着有4种水果,分别是苹果、橙子、葡萄和猕猴桃,其中有2个苹果、1个橙子和1个葡萄。

how do I print using for loop something like this: apple: 2 orange: 1 grape: 1 kiwi: 0如何使用 for 循环打印如下内容:苹果:2 橙:1 葡萄:1 猕猴桃:0

Try the code below.试试下面的代码。

 // 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) })

Try below code to get the output尝试以下代码以获取 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)

Try below code.试试下面的代码。 The first output is an object.第一个 output 是 object。 The others are strings.其他的是字符串。

 // 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