简体   繁体   English

如何从函数中返回对象?

[英]How do I return an object from a function?

I ran into this challenge for my course which i cannot crack for the life of me.我的课程遇到了这个挑战,我这辈子都无法破解。

You are given a function with a single parameter which is a nested array with objects.您将获得一个带有单个参数的函数,该参数是一个带有对象的嵌套数组。

function sortProducts (matrix) `enter code here`

The array (matrix) looks like this:数组(矩阵)如下所示:

[
  [
    { product: "MacBook", price: 1019, category: 'tech'},
    { product: "Cheerios", price: 5, category: 'food'},
  ],

  [
    { product: "Snickers", price: 1.5 , category: 'food'},
    { product: "Air Pods", price: 129, category: 'tech'},
  ],

];

Instructions: Inside the matrix array, each nested array holds objects.说明:在矩阵数组内部,每个嵌套数组都包含对象。 Each object represents a product.每个对象代表一个产品。

The function should loop over the matrix and create a new object containing the products sorted by their category.该函数应该遍历矩阵并创建一个包含按类别排序的产品的新对象。 The function should then return back this result object containing sorted products, stored in properties tech and food.然后,该函数应返回此结果对象,其中包含存储在属性 tech 和 food 中的分类产品。

The result object should have the following structure:结果对象应具有以下结构:

{
 tech:  [ { tech product }, { tech product } ],
 food:  [ { food product }, { food product } ],
};

So from my understanding the first step would be to loop over the array to create this new object.所以根据我的理解,第一步是遍历数组来创建这个新对象。 This objected would have to sort the products by category in the format (tech: 'tech product', food: 'food product'.这个反对者必须按照格式(技术:'技术产品',食品:'食品产品')对产品进行分类。

I know the answer is going to be so simple but i cant do it for the life of me.我知道答案会很简单,但我一辈子都做不到。

One way would be to flatten the array first using flatMap() and then use reduce to group by category.一种方法是首先使用flatMap()展平数组,然后使用reduce按类别分组。 Here is an example:这是一个例子:

 let arr = [ [ { product: "MacBook", price: 1019, category: 'tech'}, { product: "Cheerios", price: 5, category: 'food'}, ], [ { product: "Snickers", price: 1.5 , category: 'food'}, { product: "Air Pods", price: 129, category: 'tech'}, ], ] let result = arr.flatMap(i => i).reduce((c, p) => { c[p.category] = c[p.category] || []; c[p.category].push(p); return c; }, {}); console.log(result)

I don't understand why its called "sortProducts", your no sorting your just parsing or converting the input to another object.我不明白为什么它被称为“sortProducts”,你没有排序你只是解析或将输入转换为另一个对象。

Try something like this:尝试这样的事情:

function sortProducts(matrix){

    var result = {};

  for (let i = 0; i < matrix.length; i++) {
    const arr = matrix[i];
    
    for (let j = 0; j < arr.length; j++) {
      const obj = arr[j];

      var newObj = { product: obj.product, price: obj.price};
      
      // If result already has the category then just push the new object
      if (result[obj.category]) {
        result[obj.category].push(newObj);
        continue;
      }

      // Otherwise add the category and add the object inside an array
      // This automaticly ensures that the result.category is an array
      result[obj.category] = [newObj];

    }

  }

  return result;
}

So the solution was even simpler than i thought :'(所以解决方案比我想象的还要简单:'(

function sortProducts (matrix) {
  const tech = [];
  const food = [];
  
  for (let i = 0; i < matrix.length; i++) {
    const arr = matrix[i];

    for (let j = 0; j < arr.length; j++) {
      const product = arr[j];
      
      if ( product.category === 'tech') {
        tech.push(product);
      }
      else if (product.category === 'food') {
        food.push(product);
      }
    };
  };  
  
  return {
    tech: tech,
    food: food,
  }
}

I have no idea how I didnt figure that one out.我不知道我是怎么想出来的。 Hopefully can continue this learning curve.希望可以继续这个学习曲线。

Here is an alternative solution:这是一个替代解决方案:

 function sortCart(cart) { let sortedCart = {} cart.forEach((items) => { items.forEach((item) => { if (!sortedCart[item.category]) { sortedCart[item.category] = [] } sortedCart[item.category].push(item) }) }) return sortedCart } let cart = [ [ { product: "MacBook", price: 1019, category: 'tech'}, { product: "Cheerios", price: 5, category: 'food'}, ], [ { product: "Snickers", price: 1.5 , category: 'food'}, { product: "Air Pods", price: 129, category: 'tech'}, ], ] console.log(sortCart(cart))

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

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