搜索关键名称的开头并重命名

时间:2018-06-15 08:50:08

标签: javascript regex object replace

我想重命名所有密钥" id a1"," id a2"," id b3"等等只是名称&# 34; ID" 我正在寻找正则表达式来搜索所有当前的" id"关键名称。 我的功能必须在IE中运行:使用arrow synthax的解决方案无效。



var array1 = [{
  "id a1": 1, 
  "id a2": 2,
  name: 'ann',
  age: 24
}, {
  "id a1": 2,
  "id a2": 1,
  name: 'mark',
  age: 25
}, {
  "id b3": 3,
  "id b2": 1,
  name: 'henry',
  age: 24
}];

for (var i = 0; i < array1.length; i++) {
  var tableHeaders = Object.keys(array1[i]);

  var newObject = {};

  for (var j = 0; j < tableHeaders.length; j++) {
    var oldKey = tableHeaders[j];
    var newKey = oldKey.replace(/id/g, 'id');
    newObject[newKey] = array1[i][oldKey];
  }

  array1[i] = newObject;
}

console.log(array1);
&#13;
&#13;
&#13;

我的预期输出是这样的:

var array1 = [{"id": 1,"id": 2,name: 'ann',age: 24}, { "id": 2, "id": 1, name: 'mark',age: 25}, {"id": 3,"id": 1, name: 'henry', age: 24}];

3 个答案:

答案 0 :(得分:1)

使用Array.forEach

var array1 = [{ "id 1": 1, name: 'ann', age: 24 }, { "id 2": 2, name: 'mark', age: 25 }, { "id 3": 3, name: 'henry', age: 24 } ];

array1.forEach(o => {
  let k = Object.keys(o).find(k => k.indexOf("id") === 0);
  o.id = o[k];
  delete o[k];
});
console.log(array1);

答案 1 :(得分:0)

如果您的意思是要将它们全部重命名为id单个名称,而不是唯一名称),那么您的正则表达式只是一个咬掉你想要的是/^id \d+$/g

  • ^以匹配输入的开始
  • id匹配id后跟空格
  • \d+匹配一个或多个数字
  • $以匹配输入结束。

示例:

&#13;
&#13;
var array1 = [{ "id 1": 1, name: 'ann', age: 24 }, { "id 2": 2, name: 'mark', age: 25 }, { "id 3": 3, name: 'henry', age: 24 }, ];

for (var i = 0; i < array1.length; i++) {
  var tableHeaders = Object.keys(array1[i]);

  var newObject = {}; 

  for (var j = 0; j < tableHeaders.length; j++) {
  var oldKey = tableHeaders[j];
  var newKey = oldKey.replace(/^id \d+$/g, 'id');
  newObject[newKey] = array1[i][oldKey];
  }

  array1[i] = newObject; 
}
console.log(array1);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以通过迭代所有键值对来映射数组并构建一个新对象,并将键替换为'id''id'

var array = [{ "id 1": 1, name: 'ann', age: 24 }, { "id 2": 2, name: 'mark', age: 25 }, { "id 3": 3, name: 'henry', age: 24 } ],
    result = array.map(o =>
        Object.assign(
            ...Object.entries(o).map(([k, v]) => ({ [k.replace(/^id.+/, 'id')]: v }))
    ));

console.log(result);