[英]js: fill object with array elements using reduce()
試圖學習 reduce() 但還不能很好地理解它。 也許你的某個人可以幫助我解決我的問題。
我有一個帶有定義鍵和數組的對象。 我想使用 reduce() 用數組值填充對象鍵。
我的沙盒LINK
直到現在我嘗試了這樣的事情:
const myObj = {
first: null,
second: null,
third: null
}
const myArr = [ "abc", "def", "ghi"]
const newObj = myArr.reduce((result, value, index) => {
result[index] = value
return result
}, myObj)
console.log(newObj)
// 0: "abc"
// 1: "def"
// 2: "ghi"
// first: null
// second: null
// third: null
預期結果:
{
first: "abc",
second: "def",
third: "ghi"
}
謝謝你的幫助。
您需要將index
更改為“ index
處的對象鍵”:
const newObj = myArr.reduce((result, value, index) => {
result[Object.keys(myObj)[index]] = value
return result
}, myObj)
也就是說, zip
+ Object.fromEntries
更適合這項工作:
const zip = (...args) => args[0].map((_, i) => args.map(a => a[i])); const myObj = { first: null, second: null, third: null } const myArr = [ "abc", "def", "ghi"] const result = Object.fromEntries( zip( Object.keys(myObj), myArr ) ) console.log(result)
運行Object.keys
並從myArr
重新分配每個鍵的值。
const myObj = { first: null, second: null, third: null }; const myArr = [ "abc", "def", "ghi"]; Object.keys(myObj).forEach((k,i)=>myObj[k]=myArr[i]); console.log(myObj);
使用switch
來確定將值分配給哪個對象key
:
const myArr = ["abc", "def", "ghi"]; const newObj = myArr.reduce((result, value, index) => { let key; switch (index) { case 0: key = "first"; break; case 1: key = "second"; break; case 2: key = "third"; break; } result[key] = value; return result; }, {}); console.log(newObj);
或者,對於不依賴於描述性關鍵字的更靈活的選項:
const myArr = ["abc", "def", "ghi", "jkl", "mno"]; const newObj = myArr.reduce((result, value, index) => { result[(index + 1).toString()] = value; return result; }, {}); console.log(newObj); /* { "1": "abc", "2": "def", "3": "ghi", "4": "jkl", "5": "mno" } */
這是一個將整數轉換為序數的 SO 解決方案,即將 1 轉換為“第一”,將 2 轉換為“第二”,等等——直到“第九十九”。 這為您提供了序號鍵,並消除了對對象myObj
的需要。 通過依賴myObj
提供鍵名,您需要預先確定myArr
中有多少元素,並確保myObj
中每個元素都有一個鍵。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.