首页 > 解决方案 > 如何在对象数组中找到一个值?

问题描述

我有一个这样的对象数组:

var data = [
   {id:1,first_name:'John',last_name:'Doe',age:20,birth:'1992-01-12'},
   {id:2,first_name:'Blaan',last_name:'Adey',age:35,birth:'2001-04-16'}
];

var searchColumn = ['first_name','last_name','birth'];

这些值(searchColumn)可能会改变而不是恒定的。出于这个原因,它们必须从数组中读取

我现在想这样做:

function searchData(Val){
    var newData = [];
    if (Val){
        for (let i=0 ; i < data.length ; i++){
            searchColumn.forEach(value => {
                 if (data[i][value].includes(Val)){
                     newData.push(data[i]);
                 }
            }
        }
    }
}

searchData('L');

请指导我。

标签: javascript

解决方案


这应该做。

您不必遍历数组,您可以使用内置函数,如map,somefilter实现这一点。

var data = [
   {id:1,first_name:'John',last_name:'Doe',age:20,birth:'1992-01-12'},
   {id:1,first_name:'John',last_name:'Bal',age:20,birth:'1992-01-12'},
   {id:2,first_name:'Blaan',last_name:'Adey',age:35,birth:'2001-04-16'}
];

var searchColumn = ['first_name','last_name','birth'];

var search = (searchParam) => {
    // map here applies the function  (value) => searchColumn.some(property => value[property] === searchParam) ? value : null
    // over every value in the array & some loops through every value in the search column
    // looking for an object where one of the properties specified in searchColumn has a value that matches our search parameter
    return data.map(value => searchColumn.some(property => value[property] === searchParam) ? value : null)
        .filter(result => !!result); // here we use filter to remove the null values mapped in the map function
}

search('John');
// result -> [{id:1,first_name:'John',last_name:'Doe',age:20,birth:'1992-01-12'},
//         -> {id:1,first_name:'John',last_name:'Bal',age:20,birth:'1992-01-12'}]

更新:正如建议的,一个更好的解决方案:

var search = (searchParam) => {
    return data.filter(value => !!searchColumn.some(property => value[property] === searchParam));
}

推荐阅读