如何使用jQuery将数组对象重新排列为键值对?

时间:2016-12-08 04:40:17

标签: jquery

如果我的Array对象如下所示:

["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执行此操作吗?

1 个答案:

答案 0 :(得分: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);