如何根据密钥名称的一部分对javascript对象属性进行分组

How to group javascript object properties based on a portion of the key name?

本文关键字:属性 对象 javascript 一部分 何根 密钥      更新时间:2023-09-26

如何在这个javascript对象结构上循环,以按索引对每个键进行分组。例如CCD_ 1和CCD_。

每个_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"
}

有没有一种简单的方法可以根据密钥名称的一部分对这些密钥进行分组?

我的猜测是,您将通过_#后缀将每个键分组到一个"group对象"中。

首先,对每个成员进行迭代,并找到一种方法来提取您要查找的后缀。Regex非常适合此应用程序。

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.