使用lodash从json中删除某些属性的重复对象

时间:2017-12-13 17:00:16

标签: json lodash

我有一个类似于这个的JSON:

{
    someProperty1: "someProperty1",
    someProperty2: "someProperty2",
    hits: {
        total: 5678,
        hits: [{
            _id: "abcdef123456",
            _source: {
                deviceId: "00001234",
                longitude: -101.51729822158813,
                latitude: 21.008541584014893,
                someOtherProperty: "foo"
            }
        }, {
            _id: "abcdef123456",
            _source: {
                deviceId: "00004321",
                longitude: -101.51729822158823,
                latitude: 21.008541584014893,
                someOtherProperty: "bar"
        }, {
            _id: "abcdef123456",
            _source: {
                deviceId: "00001234",
                longitude: -101.51729822158813,
                latitude: 21.008541584014893,
                someOtherProperty: "foo"
        }
    ]
}

这个JSON来自一个相应于访问设备时更新的服务,所以我有很多重复的信息,因为设备一直都是静态的。

正如您所看到的,我有2个deviceId: 00001234寄存器,我需要做的是从我只能获得deviceIdlongitude,{{{ 1}},因为我需要使用Traccar在地图中绘制它们

所以,我的想法是首先使用Lodash过滤掉重复项,我发现了一些类似的问题,我有一些想法可以访问一些JSON的属性。

我尝试过使用其中一些脚本示例:

hits[]

我读到存在let filteredObject = _.filter(json.hits.hits, function(hit) { return _.difference(_.keys(hit._source.deviceId === "00001234")) //Won't work unless I know the deviceId beforehand }) 但是这一个返回数组中的前N个元素。

那么,我怎样才能使用Lodash获得_.firstdeviceId: "00001234"的第一次出现?

即使我得到另一个像这样的对象:

deviceId: "00004321"

1 个答案:

答案 0 :(得分:1)

这是一个使用reduce的工作示例。

let unique = x.hits.hits.reduce((acc, item) => {
  let index = _.findIndex(acc, {deviceId: item._source.deviceId});
  if(index === -1) {
    acc.push(item._source);
  }

  return acc;
}, []);

https://jsfiddle.net/W4QfJ/5880/