简体   繁体   English

从对象数组中提取 object 元素并将它们组织成数组

[英]Pulling object elements from an array of objects and organizing them into an array

After days of hairpulling, I decided to seek help:经过几天的拉扯,我决定寻求帮助:

  • I have an array of objects, one for each grocery store item.我有一组对象,每个杂货店商品一个。 Each object has 3 properties: category (string for category of item), itemName (string for item itself), and onSale (boolean whether it's on sale or not):每个 object 都有 3 个属性:category(商品类别的字符串)、itemName(商品本身的字符串)和 onSale(布尔值是否在销售):

     var itemData = [ { category: 'fruit', itemName: 'apple', onSale: false }, { category: 'canned', itemName: 'beans', onSale: false }, { category: 'canned', itemName: 'corn', onSale: true }, { category: 'frozen', itemName: 'pizza', onSale: false }, { category: 'fruit', itemName: 'melon', onSale: true }, { category: 'canned', itemName: 'soup', onSale: false }, ];
  • I need to convert it into an object whose properties are the object categories.我需要将其转换为 object,其属性为 object 类别。 Each property is an array containing values in itemName that correspond to the property:每个属性都是一个数组,其中包含与属性对应的 itemName 中的值:

     { fruit: ['apple', 'melon($)'], canned: ['beans', 'corn($)', 'soup'], frozen: ['pizza'] };
  • When I try to do it, I end up with directionally correct values, except they're repeated:当我尝试这样做时,我最终得到方向正确的值,除了它们被重复:

     { fruit: [ 'apple', 'apple', 'melon', 'melon', 'melon' ], canned: [ 'beans', 'beans', 'corn', 'corn', 'corn', 'soup', 'soup', 'soup' ], frozen: [ 'pizza', 'pizza' ] }
  • I spent hours trying to find out where I went wrong, to no avail.我花了几个小时试图找出我哪里出错了,但无济于事。 Here's my code:这是我的代码:

     function organizeItems (array){ //create output obj var output = {} //iterate over the array for(var i = 0; i < array.length; i++){ //iterate over the object in the array for(var category in array[i]){ //if value of category isn't in output add the value to output as an empty array if(output[array[i]["category"]] === undefined){ output[array[i]["category"]] = []; //if not --> push the itemName to the category } else{ output[array[i]["category"]].push(array[i]["itemName"]) } } } return output }

How can I avoid the repetition and end up with the correct values in the arrays?如何避免重复并最终在 arrays 中获得正确的值?

for(var category in array[i]){...

You don't have to iterate through the entries of each object as that will add unnecessary elements to the array like in your output 'melon', 'melon', 'melon'您不必遍历每个 object 的条目,因为这会将不必要的元素添加到数组中,例如 output 'melon', 'melon', 'melon'


You can use Array.prototype.reduce :您可以使用Array.prototype.reduce

 const itemData = [ { category: 'fruit', itemName: 'apple', onSale: false }, { category: 'canned', itemName: 'beans', onSale: false }, { category: 'canned', itemName: 'corn', onSale: true }, { category: 'frozen', itemName: 'pizza', onSale: false }, { category: 'fruit', itemName: 'melon', onSale: true }, { category: 'canned', itemName: 'soup', onSale: false }, ]; const object = itemData.reduce((acc,el) => (acc[el.category]??= [], acc[el.category].push(el.itemName + (el.onSale? '($)': '')), acc), {}) console.log(object)

You could group by category and adjust itemName .您可以按category分组并调整itemName

 const itemData = [{ category: 'fruit', itemName: 'apple', onSale: false }, { category: 'canned', itemName: 'beans', onSale: false }, { category: 'canned', itemName: 'corn', onSale: true }, { category: 'frozen', itemName: 'pizza', onSale: false }, { category: 'fruit', itemName: 'melon', onSale: true }, { category: 'canned', itemName: 'soup', onSale: false }], result = itemData.reduce((r, { category, itemName, onSale }) => { itemName += onSale? ' ($)': ''; (r[category]??= []).push(itemName); return r; }, {}); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

 var itemData = [ { category: 'fruit', itemName: 'apple', onSale: false }, { category: 'canned', itemName: 'beans', onSale: false }, { category: 'canned', itemName: 'corn', onSale: true }, { category: 'frozen', itemName: 'pizza', onSale: false }, { category: 'fruit', itemName: 'melon', onSale: true }, { category: 'canned', itemName: 'soup', onSale: false }, ]; // // expected result... // { // fruit: ['apple', 'melon($)'], // canned: ['beans', 'corn($)', 'soup'], // frozen: ['pizza'] // }; console.log( itemData.reduce((result, item) => { // destructure `itemData`'s array `item`. const { category, itemName, onSale } = item; // (create and/or) access the `category` specific array. const categoryArray = (result[category]??= []); // push the correct (depending on `onSale` state) form of a category item. categoryArray.push(`${ itemName }${ (onSale === true)? '($)': '' }`); return result; }, {}) );
 .as-console-wrapper { min-height: 100%;important: top; 0; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM