如何从一个对象制作一个数组?

时间:2017-11-09 12:58:03

标签: javascript underscore.js

我有这个对象,每个键在其末尾的下划线后面包含一个索引,所以我可以做一些事情并尝试将每个具有相同索引的一起收集并得到预期的obj,我不会知道如何用简单的java脚本的下划线来做到这一点

 class MassiveAlertAdmin extends AbstractAdmin
 {
     protected function configureFormFields(FormMapper $form)
     {
         $form
             ->with('panel name')
             ->add('fieldName')
             ->end();
     }
 }

3 个答案:

答案 0 :(得分:2)

您可以拆分对象的键以获取名称和索引。然后根据需要构建一个新对象并分配实际属性的值。

var object = { phoneNumber_0: "2", phoneNumber_1: "0", phoneType_0: "Home", phoneType_1: "Work" },
    result = [];

Object.keys(object).forEach(function (k) {
    var p = k.split('_');
    result[p[1]] = result[p[1]] || {};
    result[p[1]][p[0]] = object[k];
});

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

答案 1 :(得分:0)

我想这会做你一直在寻找的,



var obj = {
        phoneNumber_0 : "2",
        phoneNumber_1 : "0",
        phoneType_0 : "Home",
        phoneType_1 : "Work"
}
var finalArray = []
Object.keys(obj).map((key,index) => {
  if (obj['phoneNumber_' + index] || obj['phoneType_' + index])
  finalArray.push({ number: obj['phoneNumber_' + index], type:obj['phoneType_' + index]})
})

console.log(finalArray)




答案 2 :(得分:0)

这将是您的预期结果

var obj = {
  phoneNumber_0 : "2",
  phoneNumber_1 : "0",
  phoneType_0 : "Home",
  phoneType_1 : "Work"
}

var expected = []
for(var key in obj){
  if(key.indexOf('phoneNumber_') === 0){
    var kn = key.replace('phoneNumber_', '')
    expected.push({number: obj[key], type: (obj['phoneType_' + kn]||'').toLowerCase()})
  }
}

console.log(expected)