Javascript 如何创建一个新的数组的对象形式的对象没有重复?(ES6)
我想从“用户”数组中创建一个包含所有“部门”的数组,而不在ES6中重复。 我试过forEach、reduce、filter,但没有成功 用户阵列:Javascript 如何创建一个新的数组的对象形式的对象没有重复?(ES6),javascript,arrays,loops,object,ecmascript-6,Javascript,Arrays,Loops,Object,Ecmascript 6,我想从“用户”数组中创建一个包含所有“部门”的数组,而不在ES6中重复。 我试过forEach、reduce、filter,但没有成功 用户阵列: let users = [{ firstname: 'test', department: { id: 1, name: 'hello' } }, { firstname: 'test2', department: { id: 2, name: 'hell
let users = [{
firstname: 'test',
department: {
id: 1,
name: 'hello'
}
},
{
firstname: 'test2',
department: {
id: 2,
name: 'hello2'
}
},
{
firstname: 'test2',
department: {
id: 1,
name: 'hello'
}
}
]
// Expected
departments = [{
id: 1,
name: 'hello'
},
{
id: 2,
name: 'hello2'
}
] */
预期结果:
let users = [{
firstname: 'test',
department: {
id: 1,
name: 'hello'
}
},
{
firstname: 'test2',
department: {
id: 2,
name: 'hello2'
}
},
{
firstname: 'test2',
department: {
id: 1,
name: 'hello'
}
}
]
// Expected
departments = [{
id: 1,
name: 'hello'
},
{
id: 2,
name: 'hello2'
}
] */
我的:
谢谢你的帮助 您可以使用
Array.reduce()
进行以下操作:
让用户=[{
名字:'测试',
部门:{
id:1,
姓名:“你好”
}
},
{
名字:“test2”,
部门:{
id:2,
名字:“hello2”
}
},
{
名字:“test2”,
部门:{
id:1,
姓名:“你好”
}
}
];
让部门=用户。减少((acc,obj)=>{
让exist=acc.find(({id})=>id==obj.department.id);
如果(!存在){
acc.push({id:obj.department.id,name:obj.department.name});
}
返回acc;
}, []);
控制台日志(部门)代码>只需映射到部门,然后根据id进行筛选:
const ids = new Set;
const result = users
.map(user => user.department)
.filter(({ id }) => !ids.has(id) && ids.add(id));
(这是O(n),因为集合查找/插入是O(1))问题:
let users = [{
firstname: 'test',
department: {
id: 1,
name: 'hello'
}
},
{
firstname: 'test2',
department: {
id: 2,
name: 'hello2'
}
},
{
firstname: 'test2',
department: {
id: 1,
name: 'hello'
}
}
]
// Expected
departments = [{
id: 1,
name: 'hello'
},
{
id: 2,
name: 'hello2'
}
] */
您的问题是,您正在检查哪些部门与诸如Number
和string
等原语一起使用,并且不比较对象
,请尽量不要使用它,因为它与IE也不兼容
解决方案:
let users = [{
firstname: 'test',
department: {
id: 1,
name: 'hello'
}
},
{
firstname: 'test2',
department: {
id: 2,
name: 'hello2'
}
},
{
firstname: 'test2',
department: {
id: 1,
name: 'hello'
}
}
]
// Expected
departments = [{
id: 1,
name: 'hello'
},
{
id: 2,
name: 'hello2'
}
] */
您可以使用以下方法进行操作:
- 首先
map
只保留department
对象的项目
- 然后
筛选部门
以排除具有相同id的部门
演示:
let users = [{
firstname: 'test',
department: {
id: 1,
name: 'hello'
}
},
{
firstname: 'test2',
department: {
id: 2,
name: 'hello2'
}
},
{
firstname: 'test2',
department: {
id: 1,
name: 'hello'
}
}
]
// Expected
departments = [{
id: 1,
name: 'hello'
},
{
id: 2,
name: 'hello2'
}
] */
这是一个工作演示:
让用户=[{
名字:'测试',
部门:{
id:1,
姓名:“你好”
}
},
{
名字:“test2”,
部门:{
id:2,
名字:“hello2”
}
},
{
名字:“test2”,
部门:{
id:1,
姓名:“你好”
}
}
];
var deps=users.map(u=>u.department);
让结果=部门过滤器((项目,位置)=>{
返回deps.map(v=>v.id).indexOf(item.id)==pos;
});
控制台日志(结果)代码>发布您所说的从lodash尝试的代码可能是一个很好的解决方案;)@芬罗德:谢谢,不过我更喜欢香草的;)