簡體   English   中英

將數組格式化為對象javascript

[英]Format array to object javascript

我有兩個具有一定數字序列的數組( xy ),兩個數組的長度相同。 現在,我需要將兩個數組的元素組合到一個對象中。 要創建對象,我需要一個函數f如何快速將其轉換為單個對象數組

x = [1,2,3,4] 
y = [5,6,7,8]
f = function(x,y) { return { foo: x, bar: y } }
... some magic ...
result = [{ foo: 1, bar: 5},
          { foo: 2, bar: 6},
          { foo: 3, bar: 7},
          { foo: 4, bar: 8}]

當然可以使用

const array = []
for (let i = 0; i <= x.length; i++) {
    array.push(f(x[i],y[i]))
}

但是我想知道是否還有一種更“清潔”的方式? 例如使用.map? 還是這是要走的路?

-編輯-謝謝大家,不知道map也可以將索引作為參數傳遞。

您可以使用變量名稱作為鍵來構建對象,並迭代該對象的所有條目,並將數組的索引作為結果數組的對象的索引。

這適用於數組的任意長度。

 var foo = [1, 2, 3, 4], bar = [5, 6, 7, 8], result = Object .entries({ foo, bar }) .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; } 

在任何一個數組上使用reduce方法,並使用其索引從另一個數組獲取元素。

 x = [1, 2, 3, 4] y = [5, 6, 7, 8] f = function(x, y) { return x.reduce(function(acc, curr, index) { let m = {}; //creating an array which will have two keys m.foo = curr, m.bar = y[index]; acc.push(m); return acc; }, []); } console.log(f(x, y)) 

您還可以使用返回數組的map方法,因此在map回調函數內部只需創建對象並返回它

 x = [1, 2, 3, 4] y = [5, 6, 7, 8] f = function(x, y) { return x.map((item, index) => { return { foo: item, bar: y[index] } }) } console.log(f(x, y)) 

您可以使用map函數,但這只是解決這個問題的語法方法

 x = [1,2,3,4]; y = [5,6,7,8]; console.log(x.map((el,i) => ({foo:el,bar:y[i]}))); 

暫無
暫無

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

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