JavaScript替换对象数组中的键

huangapple go评论67阅读模式
英文:

Javascript Replace keys within an array of objects

问题

我有一个对象数组如下所示

[
	{contactTypeField-0: ''Index0'', firstNameField-0: ''0'', uniqueRowField-0: 0},
	{contactTypeField-1: ''Index1'', firstNameField-1: ''1'', uniqueRowField-1: 0}
]

最好的方法是替换键,即我想从每个键中删除 -0, -1, -2。因此,我期望的输出是

[
	{contactTypeField: ''Index0'', firstNameField: ''0'', uniqueRowField: 0},
	{contactTypeField: ''Index1'', firstNameField: ''1'', uniqueRowField: 0}
]

有没有一些ES6的方法可以实现这一点?

英文:

I have an array of objects as below

[
	{contactTypeField-0: 'Index0', firstNameField-0: '0', uniqueRowField-0: 0},
	{contactTypeField-1: 'Index1', firstNameField-1: '1', uniqueRowField-1: 0}
]

What is the best way to replace the keys i.e. I want to remove -0, -1, -2 from each of the keys. So I am expecting the output as

[
	{contactTypeField: 'Index0', firstNameField: '0', uniqueRowField: 0},
	{contactTypeField: 'Index1', firstNameField: '1', uniqueRowField: 0}
]

Is there some ES6 way to achieve this ?

答案1

得分: 1

您可以简单地使用正则表达式,像这样:

const data = [
  { 'contactTypeField-0': 'Index0', 'firstNameField-0': '0', 'uniqueRowField-0': 0 },
  { 'contactTypeField-1': 'Index1', 'firstNameField-1': '1', 'uniqueRowField-1': 0 }
];

const updatedData = data.map(obj => {
  const updatedObj = {};
  Object.entries(obj).forEach(([key, value]) => {
    const newKey = key.replace(/-\d+$/, '');
    updatedObj[newKey] = value;
  });
  return updatedObj;
});

console.log(updatedData);
英文:

You could simply use regex like this:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const data = [
  { &#39;contactTypeField-0&#39;: &#39;Index0&#39;, &#39;firstNameField-0&#39;: &#39;0&#39;, &#39;uniqueRowField-0&#39;: 0 },
  { &#39;contactTypeField-1&#39;: &#39;Index1&#39;, &#39;firstNameField-1&#39;: &#39;1&#39;, &#39;uniqueRowField-1&#39;: 0 }
];

const updatedData = data.map(obj =&gt; {
  const updatedObj = {};
  Object.entries(obj).forEach(([key, value]) =&gt; {
    const newKey = key.replace(/-\d+$/, &#39;&#39;);
    updatedObj[newKey] = value;
  });
  return updatedObj;
});

console.log(updatedData);

<!-- end snippet -->

答案2

得分: 1

你可以使用Array#map将对象数组转换为新数组。

对于每个对象,遍历其entries并使用String#replace来移除所需的后缀(正则表达式-\d+$匹配字符串末尾直接前面的连字符和一个或多个连续数字)。最后,使用Object.fromEntries将键值对数组转换回对象。

const arr = [
  {"contactTypeField-0": "Index0", "firstNameField-0": "0", "uniqueRowField-0": 0},
  {"contactTypeField-1": "Index1", "firstNameField-1": "1", "uniqueRowField-1": 0}
];

const res = arr.map(o => Object.fromEntries(Object.entries(o)
                  .map(([k, v]) => [k.replace(/-\d+$/, ''), v])));
console.log(res);
英文:

You can use Array#map to transform the array of objects to a new array.

For each object, map over its entries and use String#replace to remove the required suffix (the regular expression -\d+$ matches a hyphen and one or more consecutive digits directly preceding the end of the string). Finally, use Object.fromEntries to convert the array of key-value pairs back to an object.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const arr=[{&quot;contactTypeField-0&quot;:&quot;Index0&quot;,&quot;firstNameField-0&quot;:&quot;0&quot;,&quot;uniqueRowField-0&quot;:0},{&quot;contactTypeField-1&quot;:&quot;Index1&quot;,&quot;firstNameField-1&quot;:&quot;1&quot;,&quot;uniqueRowField-1&quot;:0}];
const res = arr.map(o =&gt; Object.fromEntries(Object.entries(o)
                .map(([k, v]) =&gt; [k.replace(/-\d+$/, &#39;&#39;), v])));
console.log(res);

<!-- end snippet -->

答案3

得分: 1

你可以创建一个可重用的函数,该函数可以使用名为 "pruneFn" 的函数来修剪对象的键。

const original = [
  { 'contactTypeField-0': 'Index0', 'firstNameField-0': '0', 'uniqueRowField-0': 0 },
  { 'contactTypeField-1': 'Index1', 'firstNameField-1': '1', 'uniqueRowField-1': 0 }
];

const pruneKeys = (items, pruneFn) => items
  .map(data => Object.fromEntries(Object.entries(data)
    .map(([key, value]) => [pruneFn(key), value])));

const pruned = pruneKeys(original, (key) => key.replace(/-\d+$/, ''));

console.log(pruned);

你甚至可以在键非法时抛出错误:

const original = [
  { 'contactTypeField-0': 'Index0', 'firstNameField-0': '0', 'uniqueRowField-0': 0 },
  { 'contactTypeField-1': 'Index1', 'firstNameField-99': '1', 'uniqueRowField-1': 0 }
];

const pruneKeys = (items, pruneFn) => items
  .map((data, index) => Object.fromEntries(Object.entries(data)
    .map(([key, value]) => [pruneFn(key, index), value])));

const pruned = pruneKeys(original, (key, expectedIndex) => {
  const [, newKey, actualIndex] = key.match(/(.+)-(\d+)$/);
  if (+actualIndex !== expectedIndex) {
    throw new Error(`Expected index: ${expectedIndex}, but received ${actualIndex} for ${key}`);
  }
  return newKey;
});

console.log(pruned);

请注意,这些代码示例中的内容都已翻译完毕。

英文:

You could create a reusable function that can prune keys of an object using a "prune" function i.e. pruneFn.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const original = [
  { &#39;contactTypeField-0&#39;: &#39;Index0&#39;, &#39;firstNameField-0&#39;: &#39;0&#39;, &#39;uniqueRowField-0&#39;: 0 },
  { &#39;contactTypeField-1&#39;: &#39;Index1&#39;, &#39;firstNameField-1&#39;: &#39;1&#39;, &#39;uniqueRowField-1&#39;: 0 }
];

const pruneKeys = (items, pruneFn) =&gt; items
  .map(data =&gt; Object.fromEntries(Object.entries(data)
    .map(([key, value]) =&gt; [pruneFn(key), value])));

const pruned = pruneKeys(original, (key) =&gt; key.replace(/-\d+$/, &#39;&#39;));

console.log(pruned);

<!-- language: lang-css -->

.as-console-wrapper { top: 0; max-height: 100% !important; }

<!-- end snippet -->

You could even throw an error, if a key is illegal:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const original = [
  { &#39;contactTypeField-0&#39;: &#39;Index0&#39;, &#39;firstNameField-0&#39;: &#39;0&#39;, &#39;uniqueRowField-0&#39;: 0 },
  { &#39;contactTypeField-1&#39;: &#39;Index1&#39;, &#39;firstNameField-99&#39;: &#39;1&#39;, &#39;uniqueRowField-1&#39;: 0 }
];

const pruneKeys = (items, pruneFn) =&gt; items
  .map((data, index) =&gt; Object.fromEntries(Object.entries(data)
    .map(([key, value]) =&gt; [pruneFn(key, index), value])));

const pruned = pruneKeys(original, (key, expectedIndex) =&gt; {
  const [, newKey, actualIndex] = key.match(/(.+)-(\d+)$/);
  if (+actualIndex !== expectedIndex) {
    throw new Error(`Expected index: ${expectedIndex}, but received ${actualIndex} for ${key}`);
  }
  return newKey;
});

console.log(pruned);

<!-- language: lang-css -->

.as-console-wrapper { top: 0; max-height: 100% !important; }

<!-- end snippet -->

答案4

得分: 0

使用Object.entriesreduce的另一种方法

const data = [
  {
    "contactTypeField-0": "Index0",
    "firstNameField-0": "0",
    "uniqueRowField-0": 0,
  },
  {
    "contactTypeField-1": "Index1",
    "firstNameField-1": "1",
    "uniqueRowField-1": 0,
  },
];

const res = data.map((obj) =>
  Object.entries(obj).reduce(
    (acc, [key, val]) => ({ ...acc, [key.split("-")[0]]: val }),
    {}
  )
);

console.log(res);
英文:

One more way with Object.entries and reduce

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const data = [
  {
    &quot;contactTypeField-0&quot;: &quot;Index0&quot;,
    &quot;firstNameField-0&quot;: &quot;0&quot;,
    &quot;uniqueRowField-0&quot;: 0,
  },
  {
    &quot;contactTypeField-1&quot;: &quot;Index1&quot;,
    &quot;firstNameField-1&quot;: &quot;1&quot;,
    &quot;uniqueRowField-1&quot;: 0,
  },
];

const res = data.map((obj) =&gt;
  Object.entries(obj).reduce(
    (acc, [key, val]) =&gt; ({ ...acc, [key.split(&quot;-&quot;)[0]]: val }),
    {}
  )
);

console.log(res);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月28日 01:13:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76348098.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定