英文:
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 = [
{ '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);
<!-- 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=[{"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);
<!-- 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 = [
{ '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);
<!-- 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 = [
{ '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);
<!-- language: lang-css -->
.as-console-wrapper { top: 0; max-height: 100% !important; }
<!-- end snippet -->
答案4
得分: 0
使用Object.entries
和reduce
的另一种方法
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 = [
{
"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);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论