使用array.find()在javascript数组中查找元素

时间:2019-09-17 07:23:31

标签: javascript arrays find

如何使用find在javascript数组中搜索元素?

 const array = [{
    "key1": "val1",
    "key2": "val2",
    "key3": "val3",
    "key4": "val4",
    "key5": "val5",
},
{
    "key1": "val6",
    "key2": "val7",
    "key3": "val8",
    "key4": "val9",
    "key5": "val10"
}]

我要搜索值searchvalue。我认为它将与val1相匹配,如果是,我想得到key5

array.find((element) => element.key1 === searchvalue).key5)

但是如果没有匹配的element.key1 === searchvalue,那么我想搜索key2并找到结果的key6:

array.find((element) => element.key2 === searchvalue).key5)

到目前为止,我要做的是:

var arrayElement = array.find((element) => element.key1 === 
    searchvalue)
const value =  (arrayElement !== undefined ) ? arrayElement.key5: array.find((element) => element.key2 === 
    searchvalue).key6;

3 个答案:

答案 0 :(得分:1)

您可以链接尝试找到对象并从中获取值的尝试。

var array = [{ key1: "val1", key2: "val2", key3: "val3", key4: "val4", key5: "val5" }, { key1: "val6", key2: "val7", key3: "val8", key4: "val9", key5: "val10" }],
    searchvalue = "val7",
    result = 
        (array.find(o => o.key1 === searchvalue) || {}).key5 ||
        (array.find(o => o.key2 === searchvalue) || {}).key4;

console.log(result);

答案 1 :(得分:1)

您的数据是对象数组。因此,您可以使用.some()对对象键进行另一次迭代以找到匹配项

const array = [
    {"key1": "val1","key2": "val2","key3": "val3","key4": "val4","key5": "val5",},
    {"key1": "val6","key2": "val7","key3": "val8","key4": "val9","key5": "val10",}]

const search = 'val6';
const res = (array.find(i => Object.keys(i).some(k => search === i[k])) || {}).key5
console.log(res)

答案 2 :(得分:1)

您可以循环遍历数组中每个元素的值,并将其与搜索值匹配(如果找到返回该元素),或者使用空对象作为默认值,稍后在找到的值上访问key5

const array = [{"key1": "val1","key2": "val2","key3": "val3","key4": "val4","key5": "val5",},{"key1": "val6","key2": "val7","key3": "val8","key4": "val9","key5": "val10",}]

let find = (arr,searchValue) => (arr.find(v => {
  return Object.values(v).some(value => value === searchValue)
}) || {}).key5

console.log(find(array,'val3'))
console.log(find(array,'no matching value'))