2016-12-08 75 views
1

如果我的數組對象看起來是這樣的:如何使用jQuery將數組對象重新排列爲鍵值對?

["pi|sgm", "pi|db", "pi|dlm", "groups|Homesign", "groups|Speakers", "groups|Co-speech Gesture", "pubyear|36"] 

我怎樣才能把它們分成多個基於陣列的第一個元素。例如,我需要像這樣的新數組:

["pi":["sgm", "db", "dlm"], "groups":["Homesign", "Speakers", "Co-speech Gesture"], "pubyear":["36"]] 

我們可以使用jQuery來執行此操作嗎?

+0

'鍵:value'語法是'Object'的,而不是一個'Array'的。 – 31piy

+0

我想創建對象我們的給定陣列 – Milson

回答

2

使用Array#reduce方法與String#split方法。

var data = ["pi|sgm", "pi|db", "pi|dlm", "groups|Homesign", "groups|Speakers", "groups|Co-speech Gesture", "pubyear|36"]; 
 

 
// iterate over the element to reduce to an object 
 
var res = data.reduce(function(obj, v) { 
 
    // split the value by delimitter `|` 
 
    var spl = v.split('|'); 
 
    // define the property as an array if already not defined 
 
    obj[spl[0]] = obj[spl[0]] || []; 
 
    // push the value to the array 
 
    obj[spl[0]].push(spl[1]); 
 
    // return the object reference 
 
    return obj; 
 
    // set initial value as an empty object for the result 
 
}, {}) 
 

 
console.log(res);


或者用Array#forEach方法與相同的邏輯。

var data = ["pi|sgm", "pi|db", "pi|dlm", "groups|Homesign", "groups|Speakers", "groups|Co-speech Gesture", "pubyear|36"]; 
 

 
// initialize object for result 
 
var res = {}; 
 
// iterate over the element 
 
data.forEach(function(v) { 
 
    // split the value by delimitter `|` 
 
    var spl = v.split('|'); 
 
    // define the property as an array if already not defined 
 
    res[spl[0]] = res[spl[0]] || []; 
 
    // push the value to the array 
 
    res[spl[0]].push(spl[1]); 
 
}) 
 

 
console.log(res);

+0

哪一個是最好的表演者? – Milson

+0

@Milson:不知道表現....無論如何會有微小的差異,這是微不足道的... –

+1

@Milson:https://jsperf.com/reduce-vs-foreach-pranav –

相關問題