如何将数组与值为数组的对象合并

时间:2015-11-19 18:18:12

标签: javascript arrays multidimensional-array

我有一个值数组和一个值为较小数组的对象:

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

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

对象的属性没有顺序。但如果订单不重要,我建议这个解决方案:

&#13;
&#13;
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>');
&#13;
&#13;
&#13;

对于订单证明对象,我建议将数组与对象结合使用。

&#13;
&#13;
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>');
&#13;
&#13;
&#13;