删除与 javascript 重复的对象
Remove objects if they are duplicated with javascript
如果 ID 与 lodash
_.uniqBy
相同,我正在尝试删除重复的对象。
或者这不一定是 lodash
或 _.uniqBy
,但这可能吗?
而且id值总是动态的,所以这次我想用id:123
删除对象,但其他时候会不同id
import _ from "lodash";
export default function App() {
const samples = [
{ id: 123, name: "Dan", age: 10 },
{ id: 234, name: "Jake", age: 22 },
{ id: 123, name: "Jake", age: 9 }
];
let uniq = _.uniqBy(samples, samples.name);
console.log(uniq);
return (
<div className="App">
{uniq.map((u) => (
<p>{u.id}</p>
))}
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
或者您可以查看示例代码here
您只需提供 属性 名称,在您的情况下为 name
。参见 _.uniqBy()
docs。
const samples = [{
id: 123,
name: "Dan",
age: 10
},
{
id: 234,
name: "Jake",
age: 22
},
{
id: 123,
name: "Jake",
age: 9
}
];
const unique = _.uniqBy(samples, 'name');
console.log(unique);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
编辑
编辑问题时:如果你想让它对 id
唯一,你应该传递 "id"
而不是 "name"
。
如果 ID 与 lodash
_.uniqBy
相同,我正在尝试删除重复的对象。
或者这不一定是 lodash
或 _.uniqBy
,但这可能吗?
而且id值总是动态的,所以这次我想用id:123
删除对象,但其他时候会不同id
import _ from "lodash";
export default function App() {
const samples = [
{ id: 123, name: "Dan", age: 10 },
{ id: 234, name: "Jake", age: 22 },
{ id: 123, name: "Jake", age: 9 }
];
let uniq = _.uniqBy(samples, samples.name);
console.log(uniq);
return (
<div className="App">
{uniq.map((u) => (
<p>{u.id}</p>
))}
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
或者您可以查看示例代码here
您只需提供 属性 名称,在您的情况下为 name
。参见 _.uniqBy()
docs。
const samples = [{
id: 123,
name: "Dan",
age: 10
},
{
id: 234,
name: "Jake",
age: 22
},
{
id: 123,
name: "Jake",
age: 9
}
];
const unique = _.uniqBy(samples, 'name');
console.log(unique);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
编辑
编辑问题时:如果你想让它对 id
唯一,你应该传递 "id"
而不是 "name"
。