如何在 javascript 的单个对象中推送相似的索引类型键

How to push similar index type key in single object in javascript

以下是我从结果中得到的对象类型 -

{ 
  length1: [ '45' ],
  length2: [ '42' ],
  length3: [ '21' ],
  weight1: [ '12' ],
  weight2: [ '34' ],
  weight3: [ '45' ] 
}

现在我想根据索引对它们进行分组,即 -

{length1: 45, weight1: 12}
{length1: 45, weight2: 12}
{length1: 45, weight3: 12}
..........................
..........................
..........................
{lengthn: 45, weightn: 12}

现在这可能会上升到 n

以下是我的尝试,我可以用它来打破它们,但无法组合成类似的对象,请告诉我如何实现以下结果。

var result = {}; 
result.bol = { 
  length1: [ '45' ],
  length2: [ '42' ],
  length3: [ '21' ],
  weight1: [ '12' ],
  weight2: [ '34' ],
  weight3: [ '45' ] 
};
wresl = result.bol;

            for(tip in wresl) {
                var regex1 = /length/;
                var regex2 = /width/;
                var regex3 = /height/;
                var regex4 = /weight/;
                if(regex1.test(tip)) {
                    console.log(tip);
                    console.log(result.bol[tip]);
                } else if(regex2.test(tip)) {
                    console.log(tip);
                    console.log(result.bol[tip]);
                } else if(regex3.test(tip)) {
                    console.log(tip);
                    console.log(result.bol[tip]);
                } else if(regex4.test(tip)) {
                    console.log(tip);
                    console.log(result.bol[tip]);
                }
            }

Fiddle - http://jsfiddle.net/02t92x36/1/

在 javascript 的帮助下,这里有一个解决方案:

var result = {};
result.bol = {
  length1: ['45'],
  length2: ['42'],
  length3: ['21'],
  weight1: ['12'],
  weight2: ['34'],
  weight3: ['45']
};
var wresl = result.bol;

var out=[];
var re = /length(\d+)/;
for (prop in wresl) {
  var matches=prop.match(re);
  if (matches!=null) {
    var tmp={};
    var weight = 'weight' + matches[1];
    tmp[prop] = Number(wresl[prop][0]);
    tmp[weight] = Number(wresl[weight][0]);
    out.push(tmp);
  }
}

document.write('<pre>'+JSON.stringify(out,2,1));

这应该可以解决问题:

var result = {}; 
result.bol = { 
  length1: [ '45' ],
  length2: [ '42' ],
  length3: [ '21' ],
  weight1: [ '12' ],
  weight2: [ '34' ],
  weight3: [ '45' ] 
};

out = [];

Object.keys(result.bol).forEach(function(key) {
  var m = key.match(/(\D+)(\d+)/),
      name = m[1],
      n = m[2] - 1;
  
  if(!out[n])
    out[n] = {};
  out[n][name] = Number(result.bol[key][0]);
});

document.write("<pre>"+JSON.stringify(out,0,3));

总的来说,与其像这样修复损坏的数据结构,不如从一开始就考虑一个更好的数据结构。