簡體   English   中英

如何通過在嵌套對象數組中傳遞 id 來獲取對象 JavaScript

[英]how to get object by passing id in an array of nested objects JavaScript

示例數據:

var data = [
{a:{id: "1",name: "alex",class: "1"}},
{a:{id: "2",name: "john",class: "2"}},
{a:{id: "3",name: "ketty",class: "3"}}
]

如果我將 id 作為 1 個結果傳遞:[{name:"john",class:"1"}]。

請幫我解決上述問題。

您可以使用_.find()獲取a.id路徑等於您要查找的id項目。 然后使用_.get()將項目從a屬性中取出,並省略id

注意:這將為您提供單個項目,而不是單個項目的數組。 如果你絕對需要它,你總是可以將它包裝在一個數組中。

 const { flow, find, get, omit } = _ const fn = id => flow( arr => find(arr, ['a.id', id]), // find the item which has the id item => get(item, 'a'), // extract it from a item => omit(item, 'id'), // remove the id ) const data = [{"a":{"id":"1","name":"alex","class":"1"}},{"a":{"id":"2","name":"john","class":"2"}},{"a":{"id":"3","name":"ketty","class":"3"}}] const result = fn('1')(data) console.log(result)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

使用 lodash/fp 您可以只聲明迭代對象(您希望使用的屬性),因為 lodash/fp 函數是柯里化的,並且首先迭代:

 const { flow, find, get, omit } = _ const fn = id => flow( find(['a.id', id]), get('a'), omit('id'), ) const data = [{"a":{"id":"1","name":"alex","class":"1"}},{"a":{"id":"2","name":"john","class":"2"}},{"a":{"id":"3","name":"ketty","class":"3"}}] const result = fn('1')(data) console.log(result)
 <script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>

做起來真的很簡單:-

var data = [
{a:{id: "1",name: "alex",class: "1"}},
{a:{id: "2",name: "john",class: "2"}},
{a:{id: "3",name: "ketty",class: "3"}}
]
let idToFind = 1;
let filtered = data.filter(f=>f['a']['id']==idToFind);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM