-2

Learning Bee here.

  • I have an array of nested json objects like below which i get after converting a csv file to objects and group them with a specific key

Kindly help me understand this using ES6. I am struggling to understand other similar posts using reduce, set etc. Any help is much appreciated. Thanks !

SCodes
  • 1
  • 3
  • 4
    Show us what you have tried. SO isn't a free code writing service. The objective here is for you to post your attempts to solve your own issue and others help when they don't work as expected. See [ask] and [mcve] – charlietfl Apr 01 '21 at 17:00
  • Added my code ! Thank you for your guidelines. Next time , I will make sure I sound sensible. – SCodes Apr 01 '21 at 17:48
  • Could you add more examples of the expected results? I cannot see the pattern in the single object in the – wasserholz Apr 01 '21 at 18:14
  • what is your code doing that it is not working? I noticed that you are not doing anything with `removeDuplicates` you call it but don't do anything with returned value. do you mean `return removeDuplicates...`? – chaimm Apr 01 '21 at 19:06

2 Answers2

-1

I cannot make complete sense, of what you mean by duplicates and removing them. I think, what you try to achieve is, to aggregate the SKUBACODE and SKUQUANTITY into an array and add all related metadata to that object. Assuming, that each SKUBACODE is existing only once per ORDERCLIENTREF and all other metadata is invariant.

desired_output = json_array
  .filter((group) => group != null && group.length > 0)
  .map((group) => {

  // create a hash map for sku
  const skuMap = group.reduce((acc, curr) => acc.set(curr.SKUBARCODE, SKUQUANTITY), new Map());

  const new_obj = group[0];
  new_obj.SKUBARCODE = undefined;
  new_obj.SKUQUANTITY = undefined;

  // generate output of hash map
  new_obj.ORDERLINES = [...skuMap].map(([code, quant]) {
    return {
      SKUBARCODE: code,
      SKUQUANTITY: quant
    };
  });

  return new_obj;
});

  
wasserholz
  • 1,960
  • 2
  • 20
  • 26
-1

it looks like you are trying do is just grab those 2 fields ( SKUBARCODE, SKUQUANTITY) from a group of objects. you can try it like this

  const groupOfSimilarObejcts = grouped.reduce((accumulated, currentGroup) => {
               return {
         ...currentGroup,
         ORDERLINES: [...currentGroup, {
            SKUBARCODE: currentGroup.SKUBARCODE,
            SKUQUANTITY: currentGroup.SKUQUANTITY
        }]
       };
    }, {});
chaimm
  • 192
  • 1
  • 8