如何根据匹配的ID返回一个对象数组?

时间:2017-02-23 10:25:23

标签: json lodash

我正在尝试匹配两个json文件的ID并返回匹配的对象。这些是2个json文件:

{
  "een": {
    "id": "100",
    "title": "Entertainment and stuff"
  },
  "twee": {
    "id": "107",
    "title": "Sport for everyone"
  },
  "drie": {
    "id": "108",
    "title": "Eating is good"
  }
}

这是第二个:

[
  {
    "name": "Entertainment",
    "id": "100",
    "price": 2600,
    "gifted": false
  },
  {
    "name": "Sport",
    "id": "107",
    "price": 2500,
    "gifted": false
  }
]

由于我应该获得2个匹配的idvalues:

[
  {
    "name": "Entertainment",
    "id": "100",
    "price": 2600,
    "gifted": false,
    "title": "Entertainment and stuff"
  },
  {
    "name": "Sport",
    "id": "107",
    "price": 2500,
    "gifted": false,
    "title": "Sport for everyone"
  }
]

我想知道是否有一种使用lodash或其他东西的奇特方式,并以一种非常紧凑的方式做到这一点?

2 个答案:

答案 0 :(得分:0)

一种可能的解决方案是使用merge合并两个以id为关键字的对象。这可以使用数组上的keyBy以及第一个对象的值来完成。 Intersection用于查找两个数组中的ID。

let list1 = {
  "een": {
    "id": "100",
    "title": "Entertainment and stuff"
  },
  "twee": {
    "id": "107",
    "title": "Sport for everyone"
  },
  "drie": {
    "id": "108",
    "title": "Eating is good"
  }
}

let list2 = [
  {
    "name": "Entertainment",
    "id": "100",
    "price": 2600,
    "gifted": false
  },
  {
    "name": "Sport",
    "id": "107",
    "price": 2500,
    "gifted": false
  }
]

let o1 = _.keyBy(_.values(list1), 'id');
let o2 = _.keyBy(list2, 'id');

let matchingIds = _.intersection(_.keys(o1), _.keys(o2));

let result = _.chain(o1)
    .pick(matchingIds)
    .merge(_.pick(o2,matchingIds))
    .values()
    .value()

答案 1 :(得分:0)

根据@ GruffBunny的回答,您希望获取他的结果并过滤掉o1o2中找不到的ID。

let o1 = _.keyBy(_.values(list1), 'id'));
let o2 = _.keyBy(list2, 'id');

let idsToPull = _.difference( _.map(o1, 'id'), _.map(o2, 'id')) //["108"]
let merged = _.values(_.merge(o1, o2 ));

let result = _.filter(merged, function(obj){ return _.indexOf(idsToPull, obj.id) === -1 })