我有以下数组:
data = [{
name: "Robert",
urls: [{
provider: "facebook",
url: "http://twitter.com/rob"
}]
}, {
name: "Robert",
urls: [{
provider: "youtube",
url: "http://youtube.com/robs"
}]
}, {
name: "Linda is a perfect duplicate",
urls: [{
provider: "youtube",
url: "http://youtube.com/lindaTube"
}]
}, {
name: "Linda is a perfect duplicate",
urls: [{
provider: "youtube",
url: "http://youtube.com/lindaTube"
}]
}]
我需要构建一个基于data
的新数组,如下所示:
newdata = [{
name: "Robert",
urls: [{
provider: "facebook",
url: "http://twitter.com/rob"
}, {
provider: "youtube",
url: "http://youtube.com/robs"
}]
}, {
name: "Linda is a perfect duplicate",
urls: [{
provider: "youtube",
url: "http://youtube.com/lindaTube"
}]
}];
我正在使用.merge
和.keyBy
,但始终会覆盖[urls]
。
我是这样做的:
let newdata = [];
data.forEach((val, i) => {
newdata = _.values(_.merge(
_.keyBy(newdata, 'name'),
_.keyBy(data[i], 'name')
));
});
答案 0 :(得分:1)
您可以使用lodash#groupBy
按name
对集合进行分组。使用lodash#map
将组重建为数组。使用lodash#flatMap
获取展平格式的所有网址,以便我们可以通过lodash#uniqWith
具有lodash#isEqual
比较器功能的{{3}}删除所有重复项。
var result = _(data)
.groupBy('name')
.map((group, name) => ({
name,
urls: _(group).flatMap('urls').uniqWith(_.isEqual).value()
}))
.value();
var data = [{
name: "Robert",
urls: [{
provider: "facebook",
url: "http://twitter.com/rob"
}]
}, {
name: "Robert",
urls: [{
provider: "youtube",
url: "http://youtube.com/robs"
}]
}, {
name: "Linda is a perfect duplicate",
urls: [{
provider: "youtube",
url: "http://youtube.com/lindaTube"
}]
}, {
name: "Linda is a perfect duplicate",
urls: [{
provider: "youtube",
url: "http://youtube.com/lindaTube"
}]
}];
var result = _(data)
.groupBy('name')
.map((group, name) => ({
name,
urls: _(group).flatMap('urls').uniqWith(_.isEqual).value()
}))
.value();
console.log(result);

.as-console-wrapper{min-height:100%;top:0}

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<!--
<script src="https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)"></script>
-->
&#13;
答案 1 :(得分:0)
怎么样?
var data = [{
name: "Robert",
urls: [{
provider: "facebook",
url: "http://twitter.com/rob"
}]
}, {
name: "Robert",
urls: [{
provider: "youtube",
url: "http://youtube.com/robs"
}]
}, {
name: "Linda is a perfect duplicate",
urls: [{
provider: "youtube",
url: "http://youtube.com/lindaTube"
}]
}, {
name: "Linda is a perfect duplicate",
urls: [{
provider: "youtube",
url: "http://youtube.com/lindaTube"
}]
}]
var newdata = _.reduce(data, (result, value) =>
_.values(
_.mergeWith(
_.keyBy(result, 'name'),
_.keyBy([value], 'name'),
(obj, src) =>
_.isArray(obj) ?
_.values(_.merge(_.keyBy(obj, 'provider'), _.keyBy(src, 'provider'))) :
undefined
)
), []
);
console.log(newdata);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>