使用键在数组数组中划分对象

时间:2017-03-10 15:06:15

标签: javascript arrays

考虑以下对象:

{ a1: "Foo", b1: "Boo" , c1: "Coo", a2: "Doo" , b2: "Goo", c2: "Soo", ....... c50: "Zoo" }

我想把它分成一个如下所示的数组:

[["Foo","Boo","Coo"], ["Doo","Goo","Soo"]......[ .., ..,"Zoo"]]

这样做的最佳做法是什么?

4 个答案:

答案 0 :(得分:1)

您可以使用Object.keys获取密钥,使用Array#forEach进行迭代,使用String#match获取数字部分,将其减去索引并推送值。



var object = { a1: "Foo", b1: "Boo" , c1: "Coo", a2: "Doo" , b2:"Goo", c2:"Soo", c50:"Zoo"},
    result = [];
    
Object.keys(object).forEach(function (key) {
    var i = key.match(/\d+$/) - 1;
    result[i] = result[i] || [];
    result[i].push(object[key]);
});

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 1 :(得分:1)

您可以先在reduce()上使用Object.keys()返回一个对象,然后返回该对象的map()个键,以返回值为数组的值。

var obj = { a1: "Foo", b1: "Boo" , c1: "Coo", a2: "Doo" , b2:"Goo", c2:"Soo", c50:"Zoo"}

var o = Object.keys(obj).reduce(function(r, e) {
 var newKey = e.match(/\d+/)[0]
 r[newKey] = (r[newKey] || []).concat(obj[e])
 return r
}, {})

var result = Object.keys(o).map(e => o[e])

console.log(result)

使用ES-7,你可以使用Object.values(),但它仍然有糟糕的浏览器支持,但解决方案看起来像这样。

var obj = { a1: "Foo", b1: "Boo" , c1: "Coo", a2: "Doo" , b2:"Goo", c2:"Soo", c50:"Zoo"}

var result = Object.values(Object.keys(obj).reduce(function(r, e) {
 var newKey = e.match(/\d+/)[0]
 return r[newKey] = (r[newKey] || []).concat(obj[e]), r
}, {}))


console.log(result)

答案 2 :(得分:0)

尝试这样的事情:

var obj = { a1: "Foo", b1: "Boo" , c1: "Coo", a2: "Doo" , b2:"Goo", c2:"Soo" };
var indexObj = { a: 0, b: 1, c: 2 };
var result = [];

for(var prop in obj) {
   var index = indexObj[prop[0]];
   var array = prop.match(/\d+$/) - 1;

   if(!result[array]) {
      result[array] = [];
   }

   result[array][index] = obj[prop];
}

console.log(JSON.stringify(result));
//[["Foo","Boo","Coo"],["Doo","Goo","Soo"]]

答案 3 :(得分:0)

可能你可以这样做;



var obj = { a1: "Foo", b1: "Boo" , c1: "Coo", a2: "Doo" , b2: "Goo", c2: "Soo", a3: "Hello", b3: "to", c3: "you", c50: "Zoo" },
    res = Object.keys(obj)
                .reduce(function(r,c){
                          var t = /\d+/.exec(c)[0];
                          r.t = r.t !== t ? (r.push([obj[c]]), t)
                                          : (r[r.length-1].push(obj[c]), t);
                          return r;
                        },[]);
console.log(res);