Home > Net >  Group properties with same values in js
Group properties with same values in js

Time:08-05

I have a json like this that comes from a webservice

JSON

var json = `    
       {
        "78657": "AB4",
        "78658": "AB2",
        "78659": "AB4",
        "78660": "AB2",
        "78661": "ATS",
        "78662": "DECK",
        "78663": "DECK"
       }
`;

I want this to become an obj like the one below: properties with same values must be grouped in a way that the value becomes the value of "type" property, and the number of times this value is present in the original json must be reported in quantity:

JAVASCRIPT

var obj =
    {
        items:
        [
          {
            type: 'AB4',
            quantity: 2,
          },
          {
            type: 'AB2',
            quantity: 2
          },
          {
            type: 'ATS',
            quantity:1
          },
          {
            type: 'DECK',
            quantity:2
          }
        ]
    };

CodePudding user response:

Perform a reduce the Object.values() of the input to form an index keyed by each value, counting as you go...

const json = {
  "78657": "AB4",
  "78658": "AB2",
  "78659": "AB4",
  "78660": "AB2",
  "78661": "ATS",
  "78662": "DECK",
  "78663": "DECK"
};

const index = Object.values(json).reduce((acc, v) => {
  if (!acc[v]) acc[v] = { type: v, quantity: 0 }
  acc[v].quantity  ;
  return acc;
}, {});
const obj = { items: Object.values(index) }
console.log(obj);

CodePudding user response:

const json = `    
       {
        "78657": "AB4",
        "78658": "AB2",
        "78659": "AB4",
        "78660": "AB2",
        "78661": "ATS",
        "78662": "DECK",
        "78663": "DECK"
       }
`;

const object = JSON.parse(json)

const data = {}

Object.values(object).forEach(key => {
  if (key in data) {
    data[key]  = 1
  } else {
    data[key] = 1
  }
})

const list = Object.entries(data).map(([key, value]) => ({
  type: key,
  quantity: value
}))

const final = {
  items: list
}

console.log(final)

CodePudding user response:

One-liner:

var json = `    
       {
        "78657": "AB4",
        "78658": "AB2",
        "78659": "AB4",
        "78660": "AB2",
        "78661": "ATS",
        "78662": "DECK",
        "78663": "DECK"
       }
`;


console.log({items: Object.entries(Object.entries(JSON.parse(json)).reduce((prev, [,val]) => (
    prev[val] = (prev[val] || 0)   1, prev
), {})).map(([type, quantity]) => ({ type, quantity }))});

  • Related