2015-11-19 98 views
0

我有值的数组和对象,其中的值较小的阵列:如何合并数组和对象,其中值是数组

array = [1, 2, 3, 4, 2] 
object = { 
gender: [male, female], 
grade: [7th, 8th, 9th], 
} 

我要压缩数组和对象,以使阵列中的值被分配到被键入与该对象中的值的新的对象,这样的:

targetObject = { 
    gender: [ 
    male: 1, 
    female: 2, 
    ], 
    grade: [ 
    7th: 3, 
    8th: 4, 
    9th: 2, 
    ], 
} 

我的第一刺是通过对象进行迭代,并创建一个新的数组

var newArray = []; 
for(key in object) { 
    for(i=0;i<key.length;i++){ 
    newArray.push(key[i]); 
    } 
} 

然后压缩在一起

var newObject = {}; 
for (var i = 0; i < newArray.length; i++) { 
    newObject[newArray[i]] = array[i]; 
} 

如果我的语法写我相信我在这里:

array == [1, 2, 3, 4, 2] 
object == { 
gender: [male, female], 
grade: [7th, 8th, 9th], 
} 
newArray == [male, female, 7th, 8th, 9th] 
newObject == { 
    male: 1, 
    female: 2, 
    7th: 3, 
    8th: 4, 
    9th: 2, 
} 

它看起来像我接近,但我也觉得我串起一堆脆弱的代码。有没有更好的办法?如果不是,我怎么从我NEWOBJECT去我targetObject

+0

你如何在目标探测序属性,我的意思是为什么''上1'而不是'7th' male'地图? – Grundy

+1

你的目标输出似乎不可思议,应该不会是一个对象... – epascarello

回答

0

属性没有顺序。但是,如果没有重要的顺序,我提出这个解决方案:

var array = [1, 2, 3, 4, 2], 
 
    object = { 
 
     gender: ['male', 'female'], 
 
     grade: ['7th', '8th', '9th'], 
 
    }, 
 
    newObject = {}, 
 
    i = 0; 
 

 
Object.keys(object).forEach(function (a) { 
 
    newObject[a] = newObject[a] || {}; 
 
    object[a].forEach(function (b) { 
 
     newObject[a][b] = array[i]; 
 
     i++; 
 
    }); 
 
}); 
 

 
document.write('<pre>' + JSON.stringify(newObject, 0, 4) + '</pre>');

有关订单的证明对象,我建议在组合使用数组与对象。

var array = [1, 2, 3, 4, 2], 
 
    object = [ 
 
     { gender: ['male', 'female'] }, 
 
     { grade: ['7th', '8th', '9th'] } 
 
    ], 
 
    newObject = {}, 
 
    i = 0; 
 

 
object.forEach(function (a) { 
 
    Object.keys(a).forEach(function (b) { 
 
     newObject[b] = newObject[b] || {}; 
 
     a[b].forEach(function (c) { 
 
      newObject[b][c] = array[i]; 
 
      i++; 
 
     }); 
 
    }); 
 
}); 
 

 
document.write('<pre>' + JSON.stringify(newObject, 0, 4) + '</pre>');

+0

顺序很重要,谢谢你这么多。你有什么机会评论你的代码?具体来说,newObject [b] ||是什么{}' – icicleking

+0

@icicleking,它是一个检查'newObject [b]'是否是falsey(未定义)并且需要一个逻辑或一个对象。赋值可以是对象,也可以不设置空对象。 –

0

下面的代码片段创建目标对象,它在大多数浏览器。

但是,请注意对象键保证订购。所以输出可能是这样的:

targetObject = { 
    grade: [ 
    7th: 1, 
    8th: 2, 
    9th: 3, 
    ], 
    gender: [ 
    male: 4, 
    female: 2, 
    ] 
} 

段:对象

var array = [1, 2, 3, 4, 2], 
 
    object = { 
 
     gender: ['male', 'female'], 
 
     grade: ['7th', '8th', '9th'] 
 
    }, 
 
    targetObject= {}, 
 
    i, 
 
    j, 
 
    k= 0; 
 

 
for(var i in object) { 
 
    targetObject[i]= targetObject[i] || {}; //initialize if needed 
 
    object[i].forEach(function(key) {   //iterate through the keys 
 
    targetObject[i][key]= array[k++];  //assign to the next array element 
 
    }); 
 
} 
 

 
document.querySelector('pre').textContent= JSON.stringify(targetObject, 0, 2); //show targetObject
<pre></pre>