2016-07-23 66 views
2

我有一個返回數組的功能,如下所示:轉換JavaScript數組到對象相同的鍵/值

enter image description here

但我想填充SweetAlert2對話框。

As the documentation exemplifies,所需的輸入是這樣的

inputOptions: { 
    'SRB': 'Serbia', 
    'UKR': 'Ukraine', 
    'HRV': 'Croatia' 
    }, 

我怎麼能我的數組轉換爲所需要的格式,考慮到關鍵將是一樣的價值?

所以,這樣的事情會是這個結果:

{ 
    'aaa123': 'aaa123', 
    'Açucena': 'Açucena', 
    'Braúnas': 'Braúnas', 
    [...] 
} 

我已經試過JSON.stringify,但輸出是不是我所需要的:

「[[」 AAA123" ,「Açucena 「 」布勞納斯「,」 C。 「,」「,」「,」「,」「,」「,」「,」「,」「,」

+0

也許這將有可能爆炸字符串化的結果,使得到這個結果http://imgur.com/ZZyveGb所需的輸出 – Phiter

回答

8

這可以用一個簡單的reduce的調用來做到:

// Demo data 
 
var source = ['someValue1', 'someValue2', 'someValue3', 'other4', 'other5']; 
 

 

 
// This is the "conversion" part 
 
var obj = source.reduce(function(o, val) { o[val] = val; return o; }, {}); 
 

 

 
// Demo output 
 
document.write(JSON.stringify(obj));

+0

哇,工作得很好!你能解釋一下它在做什麼嗎?聽起來太詭異 – Phiter

+0

@PhiterFernandes - 這裏沒有什麼hacky,只是一個簡單的'reduce'將數組值集合到一個對象中。 – Amit

2

這裏的關鍵是,你可以使用obj的分配屬性[ 「字符串」]技術:

function ArrayToObject(arr){ 
    var obj = {}; 
    for (var i = 0;i < arr.length;i++){ 
     obj[arr[i]] = arr[i]; 
    } 
    return obj 
} 
+0

,沒有工作 – Phiter

+0

啊,添加[0]的前參數工作。 – Phiter

1

如果您使用的是jQuery;

$.extend({}, ['x', 'y', 'z']); 

if you not;

Object.assign({}, my_array); 

另一個例子;

var arr = [{name: 'a', value: 'b', other: 'c'}, {name: 'd', value: 'e', other: 'f'}]; 

var obj = arr.reduce(function (total, current) { 
    total[ current.name ] = current.value; 
    return total; 
}, {}); 
相關問題