我有一个类似如下结构的对象(简化版):
{
"time": 100,
"complete" : true,
"results" : {
"total": 10,
"score": 3,
"results": [
{
"id" : 123,
"name": "test123"
},
{
"id" : 123,
"name": "test4554"
}
]
}
}
如何根据._uniqBy
作为唯一键,使用lodash results.results.id
对结果进行重复数据删除?
为了澄清,我希望在原始对象结构中返回重复数据删除的结果集,例如。
{
"time": 100,
"complete" : true,
"results" : {
"total": 10,
"score": 3,
"results": [
{
"id" : 123,
"name": "test123"
}
]
}
}
感谢
答案 0 :(得分:0)
只需将对象的右侧部分传递到_.uniqBy(array, [iteratee=_.identity])
函数即可实现目标。
接下来你要做的就是“结束”。 lodash uniqBy
结果和你的对象。这有点棘手。我建议您使用 ES6 Object.assign()
方法和传播运算符。
查看我的解决方案。希望这会有所帮助。
const myObj = {
"time": 100,
"complete" : true,
"results" : {
"total": 10,
"score": 3,
"results": [
{"id" : 123, "name": "test123"},
{"id" : 123, "name": "test4554"}
]
}
};
const uniq = _.uniqBy(myObj.results.results, 'id');
const resultWrapper = Object.assign({}, myObj.results, { results: [...uniq] });
const resultObj = Object.assign({}, myObj, { results: resultWrapper });
console.log( resultObj );

<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.5/lodash.min.js"></script>
&#13;
答案 1 :(得分:0)
你可以使用这样的东西
const myObj = {
time: 100,
complete : true,
results : {
total: 10,
score: 3,
results: [
{id : 123, name: "test123"},
{id : 123, name: "test4554"}
]
}
};
_.set(myObj, 'results.results', _.uniqBy(_.get(myObj, 'results.results'), 'id'))
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>
&#13;