简体   繁体   English

jQuery-将元素列表更改为关联数组

[英]jQuery - change a list of elements to an associative array

Given an associative array (of the sort returned by jQuery.serializeArray() ) like this: 给定一个关联数组(由jQuery.serializeArray()返回的排序),如下所示:

[
{ 'name': 'abc', 'value': 'aaa', '__proto__': [Object] },
{ 'name': 'def', 'value': 'bbb', '__proto__': [Object] },
{ 'name': 'abc', 'value': 'ccc', '__proto__': [Object] }
]

How can one convert this, using either jQuery or just javascript, to an associative array of name: [values] like this: 如何使用jQuery或仅使用javascript将其转换为name: [values]的关联数组name: [values]像这样:

{
   'abc': ['aaa', 'ccc'],
   'def': ['bbb']
}

This seems to essentially be the inverse of this question: Build associative array based on values of another associative array ... but in Javascript (not PHP). 这似乎基本上是这个问题的反面: 基于另一个关联数组的值构建关联数组 ...但是使用Javascript(不是PHP)。 I wasn't able to find this question on Stackoverflow, though I thought it would have been asked. 我无法在Stackoverflow上找到此问题,尽管我认为会被问到。

Thank you for reading. 感谢您的阅读。

Brian 布赖恩

You just have to iterate over the objects, check if the name exist on the result, and store or push the value, eg: 您只需要遍历对象,检查结果中是否存在name ,然后存储或推送值,例如:

var result = {};
$.each(arr, function (index, el) {
  if (!result[el.name]) {
    result[el.name] = [el.value];
  } else {
    result[el.name].push(el.value);
  }
});
//{"abc":["aaa","ccc"], "def":["bbb"]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM