[removed] filter array of objects by array of strings

后端 未结 4 1073
臣服心动
臣服心动 2020-12-03 11:54

I wonder if there is a more elegant way of doing this. Suppose i have an array of objects like this:

a = [
  {
    \"id\": \"kpi02\",
    \"value\": 10
  },
         


        
相关标签:
4条回答
  • 2020-12-03 12:31

    If you want them in the order of the array of string then

        var result = [];
    kpis.map((item) => {
        const matchedObject = a.find(
            (option) => option.id === item
        );
        result.push(matchedObject);
    });
    
    0 讨论(0)
  • 2020-12-03 12:36

    You can use indexOf in filter, like this

    var res = a.filter(function (el) {
      return kpis.indexOf(el.id) >= 0; 
    });
    

    Example

    0 讨论(0)
  • 2020-12-03 12:40

    Just make use of Array.indexOf

    var b = a.filter(function(item){return kpids.indexOf(item.id) > -1 });
    

    Array.indexOf returns the index of the argument passed in the array on which indexOf is being called on. It returns -1 if there isn't the element which we are looking for.

    So, we make sure that it index is greater than -1

    0 讨论(0)
  • 2020-12-03 12:51

    Another nice alternative is using .filter with .includes:

    var result = a.filter(item => kpis.includes(item.id))
    
    0 讨论(0)
提交回复
热议问题