2016-12-08 28 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 –

相关问题