我有一个结构类似的对象(简化版本):
{
"time": 100,
"complete" : true,
"results" : {
"total": 10,
"score": 3,
"results": [
{
"id" : 123,
"name": "test123"
},
{
"id" : 123,
"name": "test4554"
}
]
}
}基于._uniqBy是唯一的键,如何使用results.results.id去复制结果?
为了澄清,我希望在原始对象结构中返回重复的结果集。
{
"time": 100,
"complete" : true,
"results" : {
"total": 10,
"score": 3,
"results": [
{
"id" : 123,
"name": "test123"
}
]
}
}谢谢
发布于 2018-03-26 19:14:26
您可以通过将对象的正确部分传递到_.uniqBy(array, [iteratee=_.identity])函数来实现您的目标。
接下来,您要做的就是“连接”uniqBy结果和对象。这有点棘手。我建议您使用ES6 Object.assign()方法和spread运算符。
看看我的解决方案。希望这能有所帮助。
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>
https://stackoverflow.com/questions/49496903
复制相似问题