如何将数组与值为数组的对象合并
How to merge an array with an object where values are arrays
我有一个值数组和一个对象,其中值是较小的数组:
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
对象的属性没有顺序。但如果订单不重要,我建议这个解决方案:
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>');
下面的代码段创建目标对象,它将在大多数浏览器中工作。
但是,请注意,对象密钥不能保证是有序的。因此,输出可能是这样的:
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>
相关文章:
- 将数组对象传递到struts2中的操作类
- 如何使用jquery返回php-json数组对象
- 从其名称获取javascript数组对象
- 值未与数组对象绑定
- 如何按数组/对象值的倍数过滤对象数组
- 在表中显示数组对象
- 在数组对象中分组
- 将第二个或多个数组推送到数组对象 AngularJS 中
- 重新排列 JavaScript 数组/对象
- 键上的javascript数组对象过滤器
- handontable:在不更改数据数组/对象的情况下隐藏某些列
- 用于跟踪购物车可用性的Javascript数组/对象/哈希表
- 重建有角度的java脚本数组对象
- 对JSON数组对象进行排序
- 连接与数组对象相关的文本:方式和位置
- 哪些浏览器和版本支持将常见的类数组对象直接传递到fn.apply()
- 如何使用Handlebars循环数组对象和模板
- 是否可以引用JS数组/对象中的另一个元素
- Javascript中的名称索引-数组/对象
- 数组长度不等于数组对象