简体   繁体   English

如何将对象中的值分组并将它们推送到 JS 中的数组中?

[英]How can I group the values in the object and push them in an array in JS?

Basically, I am given a data set just like the one I provided below and all follow the same pattern and have the same amount of keys and values, however;基本上,我得到了一个数据集,就像我在下面提供的一样,并且都遵循相同的模式并且具有相同数量的键和值,但是; I am looking to group them in a way where the "make" stays the same, and if the array has more objects with the same "make" the "model" values are pushed into an array as shown in the example 2.我希望以“make”保持不变的方式对它们进行分组,如果数组有更多具有相同“make”的对象,则“model”值将被推送到数组中,如示例 2 所示。

I have tried attempts using a Loop, but couldn't figure out how to produce 2 different arrays for a single make.我曾尝试使用循环,但无法弄清楚如何为单个制作生成 2 个不同的数组。

const cars = [
    {
        'make': 'audi',
        'model': 'r8',
        'year': '2012'
    }, {
        'make': 'audi',
        'model': 'rs5',
        'year': '2013'
    }
];

And here is the end result that I am looking for:这是我正在寻找的最终结果:

const carByMake = [
    {
        'make': 'audi',
        'models': ['r8', 'rs5']
        'years': ['2012, 2013']
    },
];

you can do like this你可以这样做

const cars = [
  {
    make: "audi",
    model: "r8",
    year: "2012",
  },
  {
    make: "audi",
    model: "rs5",
    year: "2013",
  },
  {
    make: "audi",
    model: "rs6",
    year: "2013",
  },
  {
    make: "bmw",
    model: "x5",
    year: "2013",
  },
  {
    make: "bmw",
    model: "x6",
    year: "2013",
  },
];

let tempArr = [];
let unique = cars.map((data) => {
  let filterDataArr = tempArr.filter(
    (filterData) => filterData.make == data.make
  );
  if (filterDataArr && filterDataArr.length > 0) {
    filterDataArr[0].models = [...filterDataArr[0].models, data.model];
    filterDataArr[0].years = [...filterDataArr[0].years, data.year];
  } else {
    let dataArr = {
      make: data.make,
      models: [data.model],
      years: [data.year],
    };

    tempArr.push(dataArr);
  }
});
console.log("tempArr=>", tempArr);

There is a way more fundamental way to do what your asking.有一种更基本的方法可以满足您的要求。

This is a very basic problem, and should be solved using a basic solution.这是一个非常基本的问题,应该使用基本的解决方案来解决。 There isn't a need to filter the results, as a simple loop with an if statement can produce the results that your asking for.不需要过滤结果,因为带有 if 语句的简单循环可以产生您要求的结果。 Fundamentally, the solution for this problem is technically a sort-algorithm, just a very simple one.从根本上说,这个问题的解决方案在技术上是一种排序算法,只是一个非常简单的算法。

You could use a "for of" loop, but I feel like this is a prime example where a forEach loop shows how powerful it is.您可以使用“for of”循环,但我觉得这是一个很好的例子,其中 forEach 循环显示了它的强大功能。 ForEach is abstracted a level above your low-level while & for loops. ForEach 被抽象为比低级whilefor循环更高的级别。 That extra layer of abstraction allows a function to be passed into the forEach loop.这个额外的抽象层允许将一个函数传递到 forEach 循环中。 Each time (hence the name "each") the forEach loop iterates, the forEach's callback is executed, until the array that the forEach loop was called on has been fully iterated through (there are exceptions, but I don't want to get off track).每次(因此名称为“each”) forEach循环迭代时,都会执行 forEach 的回调,直到调用 forEach 循环的数组被完全迭代通过(有例外,但我不想下车追踪)。

You can use the forEach loop to solve your problem.您可以使用 forEach 循环来解决您的问题。 That solution is demonstrated below.该解决方案如下所示。 I documented the code w/ JSDoc so you can copy & paste it into your editor, and have the parameters & types shown in your tool-tip/hover-widget.我用JSDoc记录了代码,因此您可以将其复制并粘贴到您的编辑器中,并在您的工具提示/悬停小部件中显示参数和类型。

const cars = [
    { make: 'audi', model: 'r8', year: 2012 },
    { make: 'audi', model: 'rs5', year: 2013 },
];

/**
 * @param {string} make - The make that you want to return the models & 
           years for
 * @param {{make: string, model: string, year: number}[]} cars - An 
           array of car objects that include the model make & year
 * @return {{make: string, models: string[], years: string[]}}
 * */
function sortByMake(make, cars) {
    const models = [];
    const years = [];

    cars.forEach((car) => {
        if (car.make.toLowerCase() === make.toLowerCase()) {
            models.push(car.model);
            years.push(car.year);
        }
    });

    return { make: make, models: models, years: years };
}

console.log(sortByMake('Audi', cars));

// OUTPUT:
// $ node ./index.js
// {make: 'Audi', models: ['r8', 'rs5'], years: [2012, 2013]}

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

相关问题 如何将值推送到节点 js 中的对象数组 - How to push values to an array of object in node js 如何使用输入值创建 object 并将其推送到数组? - How can I create an object with input values and push it to array? 如何使用JavaScript push()将一组值推入数组? - How do I push a group of values to an array with Javascript push()? 将值推送到数组但作为对象? JS - Push values to array but as object? JS 如何在 JS 中破坏数组并将它们分组为另一个数组中的对象? - How can I destructing array and group them as objects in another array in JS? 如何将 object 中的特定项目分组到同一阵列中并将它们从核心阵列中删除? - How can I group specific items within an object in the same array and delete them from the core array? 如何访问嵌套数组中的多个 object 并使用 Vue 同时推送它们? - How can i access multiple object in a nested array and push them all at the same time using Vue? 如何将 object 推入数组? - How can I push an object into an array? 如何设置状态并将对象推送到数组? - How can I setState and push object to array? 如何找到相似数组对象值的总和并根据它们的值将它们分开 - How can I find the sum of of Similar array object values and separate them based on their values
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM