JavaScript How to Group Array of Nested Objects into Multiple Arrays by Nested Value group nested array mongodb,group nested array,group multidimensional-array

I am trying to convert an array to a new set of arrays by value, in this case, id.

Input

let array = [
  {"item": {"id": 111, "name": "item1"}, "qty": 1}, 
  {"item": {"id": 222, "name": "item2"}, "qty": 2},
  {"item": {"id": 222, "name": "item3"}, "qty": 3}
];

Desired Output

let newArray = [
  [{"item": {"id": 111, "name": "item1"}, "qty": 1}], 
  [{"item": {"id": 222, "name": "item2"}, "qty": 2},
   {"item": {"id": 222, "name": "item3"}, "qty": 3}]
];

Using a standard groupBy function, we can return two arrays sorted by id.

function groupItemBy(array, property) {
  var hash = {};
  for (var i = 0; i < array.length; i++) {
    if (!hash[array[i][property]]) hash[array[i][property]] = [];
    hash[array[i][property]].push(array[i]);
  }
  return hash;
}

However, when trying to map these to new arrays the nested qty data is lost.

function parse() {
  let tmp = Object.values(groupItemBy(array.map(el => el.item), "id"));

  tmp.forEach(item => {
    console.log(item);
    // do something with each item in array
  })
}

Actual Output

let newArray = [
  [{{"id": 111, "name": "item1"}], 
  [{"id": 222, "name": "item2"},
   {"id": 222, "name": "item3"}]
];

How can the integrity of the associated data be maintained while grouping the original array into an array of sorted arrays?

Answer:1

For this to work you will have to somehow tell the function where the key property is located. One can imagine very complex, nested objects, and several might have the same property names, so it even could lead to ambiguity if there is no such specification.

One way to tackle this is to make the function aware of dot-separated properties (in one string) -- a kind of "path". In your case that would be item.id. With that information the function can know where to look for the id value (in the nested object item).

Obviously the function would split that string by those dots. It can then perform a reduce on the resulting array of property names to locate the key value for each object in the array.

Here is how that could look:

let cart = [{"item": {"id": 111,"name": "item1", }, "qty": 10,}, {"item": {"id": 222,"name": "item2"},"qty": 1}, {"item": {"id": 222,"name": "item3"},"qty": 1,}];

function groupItemBy(array, property) {
    var hash = {},
        props = property.split('.');
    for (var i = 0; i < array.length; i++) {
        var key = props.reduce(function(acc, prop) {
            return acc && acc[prop];
        }, array[i]);
        if (!hash[key]) hash[key] = [];
        hash[key].push(array[i]);
    }
    return hash;
}

let grouped = Object.values(groupItemBy(cart, 'item.id'));
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Answer:2

You can try to use reduce to check, if you already seen current key, and if not - create it with empry array as a value, and push there the whole current object. Then you need to get values on result, and you good to go.

Object.values(arr.reduce((result, obj) => {
  (result[obj.item.id] || (result[obj.item.id] = [])).push(obj);
  return result;
}, {}));

Or, you can use Lodash and groupBy, then you'll have this:

Object.values(_.groupBy(arr, "item.id")));

Play with this bin to see the result in console - https://codesandbox.io/s/qx14372v74

Answer:3

I've got this firebase cloud function that I've coded to count the number of registered users vs the anynymous users. // Recalc totals user exports.recalcTotalUsers = functions.https.onRequest((req, ...

I've got this firebase cloud function that I've coded to count the number of registered users vs the anynymous users. // Recalc totals user exports.recalcTotalUsers = functions.https.onRequest((req, ...

  1. azure http function return json
  2. azure function http return xml
  3. http response return function
  4. http request function return

I have two Input fields I want to name based on user input but this name should be lowercase and spaces between words change to "-". I am doing like this $(function() { $("#name").keyup(...

I have two Input fields I want to name based on user input but this name should be lowercase and spaces between words change to "-". I am doing like this $(function() { $("#name").keyup(...

  1. auto generate name in excel
  2. auto generate name
  3. auto generate file name
  4. auto generate company name
  5. auto generate business name
  6. auto generate rap name
  7. auto generate domain name
  8. auto generate team name
  9. auto generate instagram name
  10. auto generate computer name unattend.xml
  11. auto generate last name
  12. salesforce auto generate name
  13. auto generate file name word
  14. c# auto generate name
  15. auto generate excel file name
  16. java auto generate variable name
  17. mdt auto generate computer name
  18. php auto generate file name
  19. auto-generate unit-of-order name

I am trying to scrape the following Javascript frontend website to practise my Javascript scraping skills: https://www.oplaadpalen.nl/laadpaal/112618 I am trying to find two different elements by ...

I am trying to scrape the following Javascript frontend website to practise my Javascript scraping skills: https://www.oplaadpalen.nl/laadpaal/112618 I am trying to find two different elements by ...

  1. python selenium scraping tutorial
  2. python selenium scraping example
  3. python selenium scraping
  4. python selenium scraping quora
  5. python selenium scraping javascript
  6. python selenium scraping table
  7. python selenium scrape website
  8. python selenium web scraping
  9. python selenium web scraping tutorial
  10. python selenium web scraping example
  11. python selenium webdriver scraping
  12. python selenium firefox scraping
  13. python selenium data scraping
  14. python selenium screen scrape
  15. python selenium chrome web scraping
  16. python selenium phantomjs web scraping
  17. python 3 web scraping selenium

I have an array of objects that contain data like this [{ date: "01-01-2017 00:00:00", dataField1: "", dataField2: "" }, { date: "01-02-2017 00:00:00", dataField1: "", dataField2: "" }, { ...

I have an array of objects that contain data like this [{ date: "01-01-2017 00:00:00", dataField1: "", dataField2: "" }, { date: "01-02-2017 00:00:00", dataField1: "", dataField2: "" }, { ...

  1. split array objects
  2. split array objects javascript
  3. split objects array js
  4. split array into objects
  5. split array of objects php
  6. split array of objects lodash
  7. split array of json objects
  8. split array of json objects python
  9. javascript split array of objects by property
  10. logstash split array of objects
  11. split json array into objects
  12. javascript split array into objects
  13. powershell split array of objects
  14. typescript split array of objects by property
  15. java split array of objects
  16. typescript split array of objects