![](/img/trans.png)
[英]How to create two arrays with different values in them from a JSON object?
[英]Create a JSON object from two distinct arrays
我有兩個長度相同且與索引相關的數據數組。
var a = [ "Paris", "London", "Boston"];
var b = [ 70,60,50];
我想獲得以下對象:
[{
"city":"Paris",
"temperature":70
},{
"city":"London",
"temperature":60
},{
"city":"Boston",
"temperature":50
}]
如何使用JavaScript實現此目標?
您可以為此使用“ Array.map ”
var a = [ "Paris", "London", "Boston"]; var b = [ 70,60,50]; let result = a.map((city, i) => ({ city, temperature: b[i] })) console.log(result)
為了獲得預期的結果,請使用下面的選項(假設兩個數組的長度相同)
var a = [ "Paris", "London", "Boston"]; var b = [ 70,60,50]; var result = []; a.forEach((v, i) =>{ result.push({city: v, temperature: b[i]}) }) console.log(result)
codepen- https: //codepen.io/nagasai/pen/gQWpxj
該解決方案通過避免使用硬編碼屬性來使用其他方法。
您可以通過迭代對象的條目來獲取一個對象並構建一個對象數組。 這種方法適用於任意數量的屬性。
var city = ["Paris", "London", "Boston"], temperature = [70, 60, 50], data = { city, temperature }, result = Object .entries(data) .reduce((r, [k, a]) => a.map((v, i) => Object.assign(r[i] || {}, { [k]: v })), []); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.