skip to Main Content

I’m attempting to join all keys/values that have the same number. So for example, if the key name is alfa0: 'theValueOfAlfa' and there is another key with the same number (in this case 0) beta0: 'theValueOfBeta', I would like to join them and return a object:

{
  name: 'theValueOfAlfa',
  value: 'theValueOfBeta'
}

This object:

const vls = {"lote0": "jg", "lote1": "h", "lote2": "fm", "loteQnt0": "jgvalue", "loteQnt1": "hvalue", "loteQnt2": "fmvalue" }

the expected output:

const result = [
 {
   name: 'jg',
   value: 'jgvalue'
 },
 ...
]

2

Answers


  1. Chosen as BEST ANSWER

    I create this snippet which can deal with the case. I don't believe this is the best approach, but it is a solution

    const v = {"lote0": "jg", "lote1": "h", "lote2": "fm", "loteQnt0": "jgvalue", "loteQnt1": "hvalue", "loteQnt2": "fmvalue" }
    
    const lote = Object.keys(v).filter((k, v) => {
        return k.match(/loted+$/);
    }).reduce((obj, key) => {
            obj[key] = v[key];
            return obj;
      }, {});
    
    const loteQnt = Object.keys(v).filter((k, v) => {
        return k.indexOf('loteQnt') == 0;
    }).reduce((obj, key) => {
            obj[key] = v[key];
            return obj;
      }, {});
    
    const arr = []
    
    Object.entries(lote).forEach((k, i) => {
        console.log(k[1])
        const obj = {}
        obj['lote'] = k[1]
        obj['loteQnt'] = Object.values(loteQnt)[i]    
        arr.push(obj)
    
    })
    
    result:
    [LOG]: [{
      "lote": "jg",
      "loteQnt": "jgvalue"
    }, {
      "lote": "h",
      "loteQnt": "hvalue"
    }, {
      "lote": "fm",
      "loteQnt": "fmvalue"
    }] 
    

  2. You can simply achieve this by iterating over an object to get the keys in an array and then fetch the numbers using RegEx and then perform the assignment into a new object.

    Live Demo :

    function groupValuesByNumber(obj) {
      const groupedValues = {};
    
      Object.keys(obj).forEach(key => {
        const match = key.match(/d+$/);
        if (match) {
          const number = match[0];
          !groupedValues[number] ?
            groupedValues[number] = { name: obj[key] } : groupedValues[number].value = obj[key]
        }
      })
    
      // Convert the groupedValues object to an array of objects
      const result = Object.values(groupedValues);
    
      return result;
    }
    
    const obj = {
      "lote0": "jg",
      "lote1": "h",
      "lote2": "fm",
      "loteQnt0": "jgvalue",
      "loteQnt1": "hvalue",
      "loteQnt2": "fmvalue"
    };
    
    const result = groupValuesByNumber(obj);
    
    console.log(result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search