在寻找使用键将对象转换/分组为数组的帮助时,键与其后缀(-)有所不同。
const obj = {
"name-1":"a",
"age-1":"20",
"email-1":"a@email.com",
"name-2":"b",
"age-2":"24",
"email-2":"b@email.com",
"name-3":"c",
"age-3":"22",
"email-3":"c@email1.com"
};预期结果
[
{
"name":"a",
"age":"20",
"email":"a@email.com"
},
{
"name":"b",
"age":"24",
"email":"b@email.com"
},
{
"name":"c",
"age":"22",
"email":"c@email.com"
}
]可能由于错误的搜索关键字无法找到重复的问题。
发布于 2020-04-09 23:53:38
您可以在Object.entries上运行一个reduce,并通过'-'拆分键,比如name-1, age-2等,然后返回一个对象数组。
const obj = {
"name-1":"a",
"age-1":"20",
"email-1":"a@email.com",
"name-2":"b",
"age-2":"24",
"email-2":"b@email.com",
"name-3":"c",
"age-3":"22",
"email-3":"c@email1.com"
};
const res = Object.entries(obj).reduce((acc, [key, value]) => {
const [ k, i ] = key.split('-');
acc[i - 1] = acc[i - 1] || {};
acc[i-1][k] = value;
return acc;
}, [])
console.log(res);
在上面的reduce代码中,我将key拆分为'-',它给出了一个对象的键和最后一个数组的索引。
然后检查数组中是否存在索引i - 1。如果不是,则由一个空对象初始化它。这里我使用i - 1,因为给定的对象键从1开始,而数组从0开始。
最后,我将对象值放入新创建的对象中。
发布于 2020-04-09 23:58:38
这是一个很好的算法问题,我将用ES6语法来解决它。
多亏了一些函数,比如Object.entries和reduce,你就可以做到这一点
示例:
const obj = {
"name-1":"a",
"age-1":"20",
"email-1":"a@email.com",
"name-2":"b",
"age-2":"24",
"email-2":"b@email.com",
"name-3":"c",
"age-3":"22",
"email-3":"c@email1.com"
};
const result = Object.entries(obj)
// Here we destructure the entry with on the left the key, and value on the right
.reduce((accumulator, [key, value]) => {
const [property, index] = key.split('-');
// Get the value currently being filled, or an empty object if it doesn't
// exist yet.
const entry = accumulator[index] || {};
accumulator[index] = {
// Spread the current entry to which we are adding
// the property to the object being filled
...entry,
// Dynamic key syntax
[property]: value,
};
return accumulator;
}, [])
// Remove "holes" from the array since it's indexed with given keys
.filter(value => value !== undefined);
console.log(result);
https://stackoverflow.com/questions/61124851
复制相似问题