簡體   English   中英

如何使用2個數組創建具有鍵和值的新數組?

[英]How to create new array with key and value with 2 arrays?

我有2個數組,一個用於key ,另一個用於value

想要使用這些數組創建新數組。

關鍵: [01, 02, 03]
價值: ["hi", "hello", "welcome"]
我需要的輸出:

[ 
  {"key": "1","value":"hi"},
  {"key": "2","value":"hello"},
  {"key": "3","value":"welcome"} 
]    

如何通過這種方式獲得結果。

我的代碼:

output = key.map(function(obj, index){
      var myObj = {};
      myObj[value[index]] = obj;
      return myObj;
    })    

結果:

 [
 {"1","hi"},
 {"2","hello"},
 {"3","welcome"} 
    ]

 const keys = [01, 02, 03]; const values = ['hi', 'hello', 'welcome']; const res = keys.map((key, ind) => ({ 'key': ''+key, 'value': values[ind]})); console.log(res); 

還有一個針對Object的以下方法的提議, fromEntries ,它將完全按照您的意願執行,但主流瀏覽器尚不支持它:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries

  var myArray = []; var keys = [45, 4, 9]; var cars = ["Saab", "Volvo", "BMW"]; cars.forEach(myFunction); var txt=JSON.stringify(myArray); document.getElementById("demo").innerHTML = txt; function myFunction(value,index,array) { var obj={ key : keys[index], value : value }; myArray.push(obj); } 
  <p id="demo"></p> 

您可以使用具有任意數量屬性的對象和映射新對象。

 var key = [1, 2, 3], value = ["hi", "hello", "welcome"], result = Object .entries({ key, value }) .reduce((r, [k, values]) => values.map((v, i) => Object.assign( {}, r[i], { [k]: v } )), []); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

在這里你有另一個使用reduce()的 apporach:

 let keys = [01, 02, 03]; let values = ['hi', 'hello', 'welcome']; let newArray = keys.reduce((res, curr, idx) => { res.push({'key': curr.toString(), 'value': values[idx]}); return res; }, []); console.log(newArray); 

暫無
暫無

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

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