根据条件获取该数组中另一个值的嵌套值

时间:2018-11-05 21:07:31

标签: node.js filtering lodash

我很难为此问题创建标题...

说我有这样的数据:

{"total_results":78,"resources":[{"metadata":{"verified_at":"2018-10-17T21:07:43.935Z","linkages":[{"origin":"ABC","id":"a"},{"origin":"XYZ","id":"b"}]}},{"metadata":{"verified_at":"2018-10-17T21:07:43.935Z","linkages":[{"origin":"ABC","id":"c"},{"origin":"XYZ","id":"d"}]}}]}

考虑resources字段。我想为每个数组元素输出一个包含id的数组。要获取ID,请转到链接字段(它是一个数组),然后找到具有"origin": "ABC"的元素。该元素中的id字段是应返回的ID。

此代码段有效,但似乎太冗长。必须有一种更简单的方法。

_.map(_.filter(_.flatten(_.map(body.resources, 'metadata.linkages')),['origin','ABC']), 'id')

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

var data = { "total_results": 78, "resources": [ { "metadata": { "verified_at": "2018-10-17T21:07:43.935Z", "linkages": [{ "origin": "ABC", "id": "a" }, { "origin": "XYZ", "id": "b" }] } }, { "metadata": { "verified_at": "2018-10-17T21:07:43.935Z", "linkages": [{ "origin": "ABC", "id": "c" }, { "origin": "XYZ", "id": "d" }] } } ] }

 const result = _(data.resources)
  .flatMap('metadata.linkages')
  .filter(['origin', 'ABC'])
  .map('id')
  .value()
	
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

具有链接和flatMap + filtermap

另一种方法是使用flatMapreduce

var data = { "total_results": 78, "resources": [ { "metadata": { "verified_at": "2018-10-17T21:07:43.935Z", "linkages": [{ "origin": "ABC", "id": "a" }, { "origin": "XYZ", "id": "b" }] } }, { "metadata": { "verified_at": "2018-10-17T21:07:43.935Z", "linkages": [{ "origin": "ABC", "id": "c" }, { "origin": "XYZ", "id": "d" }] } } ] }

const result = _(data.resources)
  .flatMap('metadata.linkages')
  .reduce((r,c) => (_.isEqual(c.origin, 'ABC') ? r.push(c.id) : null, r), [])

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

另一个更简洁的版本:

var data = { "total_results": 78, "resources": [{ "metadata": { "verified_at": "2018-10-17T21:07:43.935Z", "linkages": [{ "origin": "ABC", "id": "a" }, { "origin": "XYZ", "id": "b" }] } }, { "metadata": { "verified_at": "2018-10-17T21:07:43.935Z", "linkages": [{ "origin": "ABC", "id": "c" }, { "origin": "XYZ", "id": "d" }] } }] }

const result = _.reduce(data.resources, (r,c) => 
   (r.push(_.find(c.metadata.linkages, {origin: 'ABC'}).id), r), [])

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

使用ES6,您可以执行以下操作:

var data = { "total_results": 78, "resources": [{ "metadata": { "verified_at": "2018-10-17T21:07:43.935Z", "linkages": [{ "origin": "ABC", "id": "a" }, { "origin": "XYZ", "id": "b" }] } }, { "metadata": { "verified_at": "2018-10-17T21:07:43.935Z", "linkages": [{ "origin": "ABC", "id": "c" }, { "origin": "XYZ", "id": "d" }] } }] }

const result = data.resources.reduce((r,c) => 
   (r.push(c.metadata.linkages.find(x => x.origin == 'ABC').id), r), [])

console.log(result)