有没有更优雅的方式来编写这行代码?
_.chain(_.uniqBy(someArray,"someProperty.name")).map("someProperty").value();
似乎我应该能够链接它,而不是在.chain调用中嵌套lodash .uniqBy调用。
我希望以下内容有效,但不会。
_.chain(someArray).map("someProperty").value().uniqBy("name");
输入是:
someArray = [
{
aProp: '1',
anotherProp: '2',
thirdProp: '3',
someProperty: {
id: 1,
name: "john"
}
},
{
aProp: '3',
anotherProp: '4',
thirdProp: '5',
someProperty: {
id: 1,
name: "john"
}
},
{
aProp: '2',
anotherProp: 'f',
thirdProp: '6',
someProperty: {
id: 2,
name: "tom"
}
},
{
aProp: 't',
anotherProp: 'g',
thirdProp: 'f',
someProperty: {
id: 3,
name: "yacob"
}
},
];
输出应为:
[{id:1, name:"john"},{id:2, name:"tom"},{id:3, name:"yacob"}]
答案 0 :(得分:3)
实际上,你走在正确的轨道上:
_.chain(data).map('someProperty').uniqBy('id').value()
答案 1 :(得分:1)
如果你是在单链之后,可能不是在lodash中,而是在纯JS中,这是完成任务的一种方式。
var arr = [
{
aProp: '1',
anotherProp: '2',
thirdProp: '3',
someProperty: {
id: 1,
name: "john"
}
},
{
aProp: '3',
anotherProp: '4',
thirdProp: '5',
someProperty: {
id: 1,
name: "john"
}
},
{
aProp: '2',
anotherProp: 'f',
thirdProp: '6',
someProperty: {
id: 2,
name: "tom"
}
},
{
aProp: 't',
anotherProp: 'g',
thirdProp: 'f',
someProperty: {
id: 3,
name: "yacob"
}
},
],
red = arr.reduce( (p,c) => {!~p[0].indexOf(c.someProperty.id) && (p[0].push(c.someProperty.id), p[1].push(c.someProperty.name)); return p}, [[],[]]).reduce( (p,c) => p.map( (n,i) => ({id:n,name:c[i]})));
document.write("<pre>" + JSON.stringify(red,null,2) + "</pre>");
&#13;
然后我给了它一点思考,我想以下是另一种用纯JS做这个工作的方法。
red = arr.map( e => ({id: e.someProperty.id, name: e.someProperty.name})).reduce((p,c) => {!~p[0].indexOf(c.id) && (p[0].push(c.id), p[1].push(c)); return p},[[],[]])[1];
我希望看到这些的性能比较...