我很难为此问题创建标题...
说我有这样的数据:
{"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')
答案 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
和reduce
:
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)