如何將各自 Key / Value Array 合併成單一 Object ?
栏目: JavaScript · 发布时间: 7年前
内容简介:實務上 Object 的 Key 與 Value 可能來自各自的 Array,但 Function 要求傳入的是 Object,因此必須將兩個 Array 整合成單一 Object。ECMAScript 5分別有
實務上 Object 的 Key 與 Value 可能來自各自的 Array,但 Function 要求傳入的是 Object,因此必須將兩個 Array 整合成單一 Object。
Version
ECMAScript 5
Imperative
const keys = [
'Sam',
'Kevin',
'John'
];
const values = [
1,
2,
3
];
const result = {};
for(let index = 0; index < keys.length; index++)
result[keys[index]] = values[index];
console.log(result);
分別有 keys 與 values 兩個 array,Imperative 寫法就是很直覺地使用 for loop 建立 object。
Functional
const keys = [
'Sam',
'Kevin',
'John'
];
const values = [
1,
2,
3
];
const reducer = (accm, item, index) => ({...accm, [keys[index]]: item});
const result = values.reduce(reducer, {});
console.log(result);
相同的需求,若使用 Functional 寫法,就會使用 Array.prototype.reduce() 。
reduce() 其實有較少使用的第三個 argument: currentIndex ,傳入目前 item 的 index。
...accm 為 ECMAScript 2015 的 Object Spread,將展開目前的 object。
[keys[index]]: value
乍看很 tricky,原本 [variable]: value 為新增 object 的一對 key / value,將 variable 以 keys[index] 取代而已。
Conclusion
- 若要將 array 轉成 object,則
reduce()為標準思考方式
Reference
MDN , Array.prototype.reduce()
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Introduction to Linear Optimization
Dimitris Bertsimas、John N. Tsitsiklis / Athena Scientific / 1997-02-01 / USD 89.00
"The true merit of this book, however, lies in its pedagogical qualities which are so impressive..." "Throughout the book, the authors make serious efforts to give geometric and intuitive explanations......一起来看看 《Introduction to Linear Optimization》 这本书的介绍吧!