0

I am getting data like below :

data.filter = {
    selectedFilterItems: [
        {
            name: "0-435",
            categoryId: "0_435",
            code: "price",
            totalItems: 1,
        },
        {
            name: "MULTI",
            categoryId: "7608",
            count: 633,
            code: "color",
            subcategories: [],
            totalItems: 1,
        },
        {
            name: "Pastel Tie Dye",
            categoryId: "566962",
            count: 1,
            code: "color",
            subcategories: [],
            totalItems: 1,
        },
    ],
    totalItems: 3,
};

I need to create a json like below, where type will be the "code" i get from above data (i.e data.filter) & the value will be comma seperated for common code.

Desired Output :

filters: [
    {
      type: 'price',
      value: '0-435'
    }
]

exg for color there will be only one type = color & its value will be "MULTI,Pastel Tie Dye".

if only one distinct code is there in data.filter then only that data will be in filters.

Here is the code which i am trying

if(data.filter) {
const selectedFilterItems = data.filter.selectedFilterItems.reduce((property, attribute) => {
    if (property[attribute.code]) {
      property[attribute.code].value += `,${attribute.name}`;
    } else {
      property[attribute.code] = { type: attribute.code, value: attribute.name };
    }
    return property;
    }, {});
    filter_data = Object.values(selectedFilterItems);
  }

i need to add to the "filter_data" variable.

{
      type: 'category',
      value: '7608' //  where the value will be there "selectedFilterItems's any of the property's categoryId's value.
}
  • Should the `sorts` property be in the desired output? It's not part of the input – A_A Aug 25 '21 at 07:48
  • That's fine, its static. i have removed from desired data. –  Aug 25 '21 at 07:49
  • SO isn't a code writing service, what have you tried already to accomplish this? https://stackoverflow.com/help/minimal-reproducible-example – Drew Reese Aug 25 '21 at 07:50
  • Have you taken a look at [arr.reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)? If not, take a look at the examples with objects – A_A Aug 25 '21 at 07:50
  • Yes let me updated question, i am trying to make it work may be i need to loop through the "selectedFilterItems" –  Aug 25 '21 at 07:50
  • Let me try the code. Also any answers to this question are appreciated –  Aug 25 '21 at 07:58

2 Answers2

0

You can use reduce() to filter the data and extract it with Object.values()

const data = { selectedFilterItems: [ { name: "0-435", categoryId: "0_435", code: "price", totalItems: 1, }, { name: "MULTI", categoryId: "7608", count: 633, code: "color", subcategories: [], totalItems: 1, }, { name: "Pastel Tie Dye", categoryId: "566962", count: 1, code: "color", subcategories: [], totalItems: 1, }, ], totalItems: 3, };

const groupByData = data.selectedFilterItems.reduce((acc, b) => {
  if (acc[b.code]) {
    acc[b.code].value += `,${b.name}`;
  } else {
    acc[b.code] = { type: b.code, value: b.name };
  }
  return acc;
}, {});

const output = Object.values(groupByData);

console.log(output);
ikhvjs
  • 5,316
  • 2
  • 13
  • 36
  • Thanks for the answer, the value for "type" property should be the "code" 's value from the input. –  Aug 25 '21 at 08:06
  • @devhs, updated. I have some typo. – ikhvjs Aug 25 '21 at 08:06
  • The "acc & b" used in above code are just random argument names right ? –  Aug 25 '21 at 08:06
  • @devhs, yes. it is up to you. – ikhvjs Aug 25 '21 at 08:07
  • Also what is the use of the $ in acc[b.code].value += `,${b.name}`; ? –  Aug 25 '21 at 08:07
  • 1
    @devhs, if the `acc[b.code]` exist in the `acc` , you don't need to reassign a new object for it and you just want to append the value with name properties. and when you append the value, you want to add `,` in between. – ikhvjs Aug 25 '21 at 08:09
  • Very helpful, thankyou very much. let me try it with code to see it works. –  Aug 25 '21 at 08:10
  • There will be no chance of any error right in this ? –  Aug 25 '21 at 08:10
  • @devhs, if `code` and `name` always exist in your data, there should be no error. – ikhvjs Aug 25 '21 at 08:12
  • I need to add {type: 'category',value: 'Tops'} this value to the "output" where the value will be there "selectedFilterItems's any of the property's categoryId's value. –  Aug 25 '21 at 08:37
  • Can you please advice me on that ? –  Aug 25 '21 at 08:38
  • @devhs , What if the `categoryId` is duplicated? – ikhvjs Aug 25 '21 at 08:51
0

let data = {};

data.filter = {
    selectedFilterItems: [
        {
            name: "0-435",
            categoryId: "0_435",
            code: "price",
            totalItems: 1,
        },
        {
            name: "MULTI",
            categoryId: "7608",
            count: 633,
            code: "color",
            subcategories: [],
            totalItems: 1,
        },
        {
            name: "Pastel Tie Dye",
            categoryId: "566962",
            count: 1,
            code: "color",
            subcategories: [],
            totalItems: 1,
        },
    ],
    totalItems: 3,
};

let filters = [];
let codes = []

data.filter.selectedFilterItems.forEach((elem)=>codes.push(elem.code));  //store all codes in an array

codes = [...new Set(codes)]   //create a set of codes which will only contain unique entities

codes.forEach(code=>{                              //Iterate over the codes
  let obj = {}, val="";
  data.filter.selectedFilterItems.forEach(elem=>{  //Iterate over each selectedFilterItems object
    if(elem.code === code){
      val += elem.name + ",";                  // Add the name to val if the code matches
    }
  })
  val = val.substring(0, val.length-1);  //Remove last char that will be comma
  obj["type"] = code;
  obj["value"] = val;
  filters.push(obj)  
})

console.log(filters)
TechySharnav
  • 4,869
  • 2
  • 11
  • 29