簡體   English   中英

如何將數組與值是數組的對象合並

[英]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];
}

如果我的語法是write,我相信我在這里:

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

以下代碼段創建了目標對象,它將在大多數瀏覽器中運行。

但是,請注意, 不能保證對象鍵是有序的。 因此輸出可能是這樣的:

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> 

對象的屬性沒有順序。 但是如果順序不重要,則我提出以下解決方案:

 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>'); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM