0

Can I filter or extract the values of an object, based on a value?

For example [10, 19] would return Bill and Sam.

 [ { "id": 10, "nice_name": "Bill" }, 
    { "id": 12, "nice_name": "Dan"}, 
    { "id": 18, "nice_name": "Tony" },
    { "id": 19, "nice_name": "Sam" }, 
]

Thanks/

LeBlaireau
  • 17,133
  • 33
  • 112
  • 192

6 Answers6

3

You can chain filter then map functions :

const mySearch = [10, 19]
const result = myArray.filter(elem => mySearch.indexOf(elem.id) > -1) // filter by id
                      .map(elem => elem.nice_name) // return the nice_name only for each entry
// result is now ['Bill', 'Sam']
Lythom
  • 31
  • 1
1

You can use Array.prototype.filter() function:

const data = [ { "id": 10, "nice_name": "Bill" }, 
    { "id": 12, "nice_name": "Dan"}, 
    { "id": 18, "nice_name": "Tony" },
    { "id": 19, "nice_name": "Sam" }, 
]

const result = data.filter(o => ~[10, 19].indexOf(o.id))
// ~[10, 19].indexOf(o.id) is equivalent to [10, 19].indexOf(o.id) > -1
madox2
  • 49,493
  • 17
  • 99
  • 99
0

Using only javascript you can do something like this.

var size = a.length; //a -> your array
var inputSize = input.length; // -> the search array
var thePeople = []; //where you will store the names that match
for(var i = 0; i < size; i++) {  //cycle your array
    for(var j = 0; j < inputSize; j++) { //cycle the search array
    if(a[i].id === input[j]) { //check if there is a match on id
        thePeople.push(a[i].nice_name); //save the name into a new array
    }
  }
}

here is a fiddle https://jsfiddle.net/xo5vxwo0/

rule
  • 281
  • 1
  • 8
0

indexOf to find an element in array .

arr=[ { "id": 10, "nice_name": "Bill" }, 
    { "id": 12, "nice_name": "Dan"}, 
    { "id": 18, "nice_name": "Tony" },
    { "id": 19, "nice_name": "Sam" }, 
]
var fill=[10,19];
var ans=[];

arr.map(function(a){
    if(fill.indexOf(a["id"])>-1)
    ans.push(a["nice_name"]);
})

console.log(ans);
*{
background-color:pink;
}
Mahi
  • 1,707
  • 11
  • 22
0
var data = [ { "id": 10, "nice_name": "Bill" }, 
         { "id": 12, "nice_name": "Dan"}, 
         { "id": 18, "nice_name": "Tony" },
         { "id": 19, "nice_name": "Sam" }, 
]

var idWant  = [10,19];
var content = '';   

for(var keysWant in idWant){
    var number = idWant[keysWant];  
    for(var keysData in data){   
        if(number == data[keysData]['id']){   
            content += data[keysData]['nice_name'] + ' ';
        } 
    }  
}  

console.log(content);
Maciej
  • 1
  • 2
0

One might use a single reduce instead of filter.map chain.

var arr = [ { "id": 10, "nice_name": "Bill" }, 
            { "id": 12, "nice_name": "Dan"}, 
            { "id": 18, "nice_name": "Tony" },
            { "id": 19, "nice_name": "Sam" }, 
          ],
    src = [10,19],
 result = arr.reduce((r,o) => src.includes(o.id ) ? r.concat(o.nice_name) : r,[]);
console.log(result);
Redu
  • 25,060
  • 6
  • 56
  • 76