从包含特定值的对象的多维数组返回数组对象

时间:2019-06-13 12:42:19

标签: javascript arrays

我正在尝试创建一个功能类似于搜索机制的函数,该函数遍历对象数组并返回包含此数组中特定值(搜索参数)的特定数组对象

var jobs= [
  {
    "startDate": "5/2017",
    "endDate": null,
    "isCurrent": true,
    "seniority": "Senior",
  },
  {
    "startDate": "5/2013",
    "endDate": "5/2019",
    "isCurrent": false,
    "seniority": "Junior",
  },
]

我想创建一个函数,在其中提供数组,数组键和数组值,即

nameOfFunction(jobs,"seniority","Senior")

它返回/记录

{"startDate": "5/2017","endDate": null,"isCurrent": true,"seniority": "Senior",},

4 个答案:

答案 0 :(得分:1)

数组的filter方法可以做到这一点,但是如果要包装它,可以执行以下操作……

version: "3"

services:

  gradle:
    depends_on:
      - elasticsearch

  elasticsearch:
    image: elasticsearch{6/7}

答案 1 :(得分:1)

您可以使用template <std::size_t, typename T> using always_t = T; template <typename Seq> class DiscreteFunImpl; template <std::size_t ... Is> class DiscreteFunImpl<std::index_sequence<Is...>> { private: std::function<int (always_t<Is, int>...)> f; public: DiscreteFunImpl(std::function<int (always_t<Is, int>...)> f): f(f) {} int eval(const array<int, sizeof...(Is)>& x) const { return f(x[Is]...); } }; template <std::size_t N> using DiscreteFun = DiscreteFunImpl<std::make_index_sequence<N>>;

filter

编辑:

var jobs= [
  {
    "startDate": "5/2017",
    "endDate": null,
    "isCurrent": true,
    "seniority": "Senior",
  },
  {
    "startDate": "5/2013",
    "endDate": "5/2019",
    "isCurrent": false,
    "seniority": "Junior",
  },
]


const findObject = (obj, prop, value) => obj.filter(obj => obj[prop] === value)

console.log(findObject(jobs, 'seniority', 'Senior'))

答案 2 :(得分:0)

您可以在传入的数组中使用filter方法。在这里,我还使用destructuring assignment从传入的v中获取当前对象的值(key)。然后,我将对象(v)的值与传递给函数的val进行比较,以查看是否应将其保留在新数组中。

请参见以下示例:

const jobs= [
  {
    "startDate": "5/2017",
    "endDate": null,
    "isCurrent": true,
    "seniority": "Senior",
  },
  {
    "startDate": "5/2013",
    "endDate": "5/2019",
    "isCurrent": false,
    "seniority": "Junior",
  },
];

const filterArr = (arr, key, val) => 
  arr.filter(({[key]:v}) => v===val);
  
console.log(filterArr(jobs, "seniority", "Senior"));

答案 3 :(得分:0)

您可以尝试一下,

var jobs= [
  {
    "startDate": "5/2017",
    "endDate": null,
    "isCurrent": true,
    "seniority": "Senior",
  },
  {
    "startDate": "5/2013",
    "endDate": "5/2019",
    "isCurrent": false,
    "seniority": "Junior",
  },
];

// This function will return array of filtered elements
function searchArray(array,propertyKey,propertyValue){
  return array.filter(function(a){
      return a[propertyKey] === propertyValue;
  });
}

console.log(searchArray(jobs, 'seniority', 'Senior'));

// With new way

function searchArrayNewMethod(array,propertyKey,propertyValue){
  return array.filter( a => a[propertyKey] === propertyValue);
}


console.log(searchArrayNewMethod(jobs, 'seniority', 'Senior'));