如何通过在嵌套对象的JavaScript数组中传递id来获取对象

时间:2020-03-02 10:49:30

标签: javascript ecmascript-6 lodash

示例数据:

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”}]。

请帮我解决上述问题。

2 个答案:

答案 0 :(得分:0)

您可以使用_.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>

答案 1 :(得分:-1)

它真的很简单:-

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);