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

How to merge an array with an object where values are arrays

本文关键字:数组 对象 合并      更新时间:2023-09-26

我有一个值数组和一个对象,其中值是较小的数组:

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>