【问题标题】:How to group javascript object properties based on a portion of the key name?如何根据键名的一部分对 javascript 对象属性进行分组?
【发布时间】:2014-09-30 00:15:46
【问题描述】:

我如何循环遍历这个 javascript 对象结构以按索引对每个键进行分组。例如 mobile_1desktop_1 应该被分组。

每个_1 应该在一起,_2。等等。

这是对象:

{
"mobile_1": "source/test.jpg",
"mobile_2": "source/test.jpg",
"mobile_3": "source/test.jpg",
"desktop_1": "source/test.jpg",
"desktop_2": "source/test.jpg",
"desktop_3": "source/test.jpg",
"link_1": "#",
"link_2": "#",
"link_3": "#",
"tag_1": "Test 1",
"tag_2": "Test 2",
"tag_3": "Test 3",
"linkLabel_1": "Test 1 Go",
"linkLabel_2": "Test 2 Go",
"linkLabel_3": "Test 3 Go",
"title_1": "Test 1 Desc",
"title_2": "Test 2 Desc",
"title_3": "Test 3 Desc"
}

有没有一种简单的方法可以按键名的一部分对这些键进行分组?

【问题讨论】:

  • 我认为您需要澄清问题,也许更好地解释您希望帮助解决的问题;正如所写,我想我不知道你想要什么。
  • 哦抱歉,我更新了我的问题,我需要在当前结构中按索引号对键进行分组。
  • 你的意思是"_1" = { mobile: source/test.jpg, desktop: ..., tag: ..., linkLabel: ..., title: "Test 1 Desc" }的意思吗?

标签: javascript json rest


【解决方案1】:

我的猜测是您将每个键(通过它的 _# 后缀)放入“组对象”中。

首先,遍历每个成员并找到一种方法来提取您要查找的后缀。正则表达式非常适合此应用程序。

for(var key in src){
  var key.match(/_\d/);
  // ...

接下来,要精通括号符号。它允许您通过字符串或字符串变量“动态”访问属性;以及其他子对象。

// assume suffix==="_1" and key==="mobile_1" <-- Still in the for-loop
group[suffix][key] = src[key];
/* ^- Same as group["_1"]["mobile_1"] = src["mobile_1"];
   ^- Same as group._1.mobile_1 = "source/test.jpg"
   ^- Same as group = { "_1": { "mobile_1": "source/test.jpg" }};
*/

工作示例:

var group = { };

src = {
"mobile_1": "source/test.jpg",
"mobile_2": "source/test.jpg",
"mobile_3": "source/test.jpg",
"desktop_1": "source/test.jpg",
"desktop_2": "source/test.jpg",
"desktop_3": "source/test.jpg",
"link_1": "#",
"link_2": "#",
"link_3": "#",
"tag_1": "Test 1",
"tag_2": "Test 2",
"tag_3": "Test 3",
"linkLabel_1": "Test 1 Go",
"linkLabel_2": "Test 2 Go",
"linkLabel_3": "Test 3 Go",
"title_1": "Test 1 Desc",
"title_2": "Test 2 Desc",
"title_3": "Test 3 Desc"
}

for(var key in src){
  var suffix = key.match(/_\d/);
  // The following will create the new "group" in the 
  // master group variable if it doesn't exist
  if(!group[suffix]){ group[suffix] = {}; }
  group[suffix][key] = src[key];
}

console.log(group);              //grouped objects printed to log
alert(JSON.stringify(group) );   //sent to alert box so snippet runs.

【讨论】:

  • 谢谢!是的,像这样,我只需要使对象动态,但谢谢,这就是我要找的!
  • @Randell 您可以使用括号符号的相同概念来检查该子组对象是否存在,如果不存在则添加它。我将它添加到 sn-p。
  • 酷!我也做了一个动态的,但你的更新更简单易懂,谢谢你,伙计! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-05
  • 1970-01-01
  • 2021-11-14
  • 1970-01-01
相关资源
最近更新 更多