我有一个对象数组要转换为一个对象数组,该数组的唯一值分配给相同的键。
我怎样才能得到这个输出?
输入//
let users = [
{ id: 1, name: "Alan", surname: "Davis", age: 34, isAdmin: 'yes'},
{ id: 2, name: "John", surname: "Doe", age: 35, isAdmin: 'no'},
{ id: 3, name: "Monica", surname: "Bush", age: 25, isAdmin: 'no'},
{ id: 4, name: "Sandra", surname: "Back", age: 23, isAdmin: 'no'},
{ id: 5, name: "Jacob", surname: "Front", age: 34, isAdmin: 'yes'},
];
//输出
let unique = {
id: [1, 2, 3 ,4 ,5],
name: ['Alan', 'John', 'Monica', 'Sandra', 'Jacob'],
surname: ['Davis', 'Doe', 'Bush', 'Back', 'Front'],
age: [34, 35, 25, 23],
isAdmin: ['yes', 'no'],
}
您可以使用array .prototype.reduce(),并使用array .prototype. foreach()对所有项目进行迭代,并使用Set
创建唯一数组。代码:
const users = [{ id: 1, name: 'Alan', surname: 'Davis', age: 34, isAdmin: 'yes' },{ id: 2, name: 'John', surname: 'Doe', age: 35, isAdmin: 'no' },{ id: 3, name: 'Monica', surname: 'Bush', age: 25, isAdmin: 'no' },{ id: 4, name: 'Sandra', surname: 'Back', age: 23, isAdmin: 'no' },{ id: 5, name: 'Jacob', surname: 'Front', age: 34, isAdmin: 'yes' },]
const unique = users.reduce((a, c) => (
Object
.entries(c)
.forEach(([k, v]) => a[k] = [...new Set([...(a[k] || []), v])]),
a
), {})
console.log(unique)
有一种方法
- 遍历数组中第一个对象的键,生成一个键列表
- 创建对应值的数组。
- 将键和值包装回对象
let users = [
{ id: 1, name: "Alan", surname: "Davis", age: 34, isAdmin: 'yes'},
{ id: 2, name: "John", surname: "Doe", age: 35, isAdmin: 'no'},
{ id: 3, name: "Monica", surname: "Bush", age: 25, isAdmin: 'no'},
{ id: 4, name: "Sandra", surname: "Back", age: 23, isAdmin: 'no'},
{ id: 5, name: "Jacob", surname: "Front", age: 34, isAdmin: 'yes'},
];
let unique = Object.fromEntries(
Object.keys(users[0]).map(k =>
[k, users.map(u => u[k]).filter((value, i, arr) => arr.indexOf(value) === i)]
)
);
console.log(unique);