【问题标题】:how to get object by passing id in an array of nested objects JavaScript如何通过在嵌套对象数组中传递 id 来获取对象 JavaScript
【发布时间】:2020-03-02 10:49:30
【问题描述】:

示例数据:

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

请帮我解决上述问题。

【问题讨论】:

  • 你确定是[{name:"john,class:"1"}] 不是[{name:"alex,class:"1"}] 吗?
  • 是这样的[{name:"john",class:"1"}]
  • 您的意思是 [{name:"john",class:"2"}] 吗?
  • 这能回答你的问题吗? Find by key deep in a nested array
  • 请编辑您的问题并清楚地解释您的问题

标签: javascript ecmascript-6 lodash


【解决方案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>

【讨论】:

    【解决方案2】:

    做起来真的很简单:-

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

    【讨论】:

      猜你喜欢
      • 2019-01-12
      • 2021-11-30
      • 1970-01-01
      • 2022-11-24
      • 1970-01-01
      • 1970-01-01
      • 2018-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多