简体   繁体   English

如何使用 JavaScript 从多维数组中获取动态数组元素?

[英]How to get dynamic array elements from multidimensional array using JavaScript?

Input Data:输入数据:

[
  {
    'id': 10,
    'name': 'kohli',
    'email': 'kohli@email.com',
    'phone': '8080808080'
  },
  {
    'id': 11,
    'name': 'john',
    'email': 'john@email.com',
    'phone': '987679090'
  }
]

I want to fetch particular elements using above multidimensional array, but need to call dynamically.我想使用上述多维数组获取特定元素,但需要动态调用。

Example:-例子:-

function getDataFromArray(Params){
  // login here
}

1. getDataFromArray(['id','name']) => 1. getDataFromArray(['id','name']) =>

  [
      {
        'id': 10,
        'name': 'kohli'
      },
      {
        'id': 11,
        'name': 'john'
      }
    ]

In this example we want to fetch only id & name.在这个例子中,我们只想获取 id 和 name。

2. getDataFromArray(['name','email']) => 2. getDataFromArray(['name','email']) =>

  [
      {
        'name': 'kohli',
        'email': 'kohli@email.com'
      },
      {
        'name': 'john',
        'email': 'john@email.com'
      }
    ]

In this example we want to fetch name & email only.在这个例子中,我们只想获取姓名和电子邮件。

So can we manage this ?那么我们可以管理这个吗?

Pretty straight forward map / reduce operation非常直接的映射/减少操作

 const arr = [ { 'id': 10, 'name': 'kohli', 'email': 'kohli@email.com', 'phone': '8080808080' }, { 'id': 11, 'name': 'john', 'email': 'john@email.com', 'phone': '987679090' } ] function getDataFromArray(params) { return arr.map(item => params.reduce((o, param) => ({ ...o, [ param ]: item[param] }), {})) } console.log("['id','name'] =>", getDataFromArray(['id','name'])) console.log("['name','email'] =>", getDataFromArray(['name', 'email']))
 .as-console-wrapper{max-height: 100% !important;}

This maps each entry in the array to a new object that is constructed by reducing params to an object with keys from params and values from the objects in the array.数组中的每个条目映射到一个新对象,该对象是通过params减少到一个对象来构造的,该对象具有来自params键和来自数组中对象的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM