Skip to content Skip to sidebar Skip to footer

Filter An Array Of Objects And Extract Its Property By Using An Array Of Keys

im having this problem which i cant wrap around my head, much better if put in a code. //Array of objects sample var objects = [{id:1, name:'test1'}, {id:2, name:'test2'}, {id:3, n

Solution 1:

You could map the objects and ren map the wanted keys for getting the name.

var objects = [{ id: 1, name: 'test1' }, { id: 2, name: 'test2' }, { id: 3, name: 'test3' }],
    arrayOfKeys = [3, 1],
    result = arrayOfKeys.map((map =>id => map.get(id).name)(newMap(objects.map(o => [o.id, o]))));
    
console.log(result);

Solution 2:

I assume you need to map array numbers to id properties? Here's the code where you map through numbers and find inside your array to handle situations when there's no such id in objects array:

var objects = [{id:1, name:'test1'}, {id:2, name:'test2'}, {id:3, name: 'test3'}];
var arrayOfKeys = [3,1];

var res = arrayOfKeys.map(key => {
  var found = objects.find(o => o.id == key);
  return found ? found.name : false;
})

console.log(res)

Solution 3:

let objects = [{id:1, name:'test1'}, {id:2, name:'test2'}, {id:3, name: 'test3'}, {id:4, name:'test4'}],
    arrayOfKeys = [3,1,4];

let result = objects.reduce((res, obj) => {    // loop over the array of objectslet index = arrayOfKeys.indexOf(obj.id);     // check if the current object's id is in the array of keysif(index !== -1) {                           // if it's there
    res.push(obj.name);                        // then add the current object's name to the result array
    arrayOfKeys.splice(index, 1);              // remove its id from the array of keys so we won't search for it again (optional, slightly better than leaving it there)
  }
  return res;
}, []);

console.log(result);

Solution 4:

I think you were on the right track with the filter. You can make it readable and concise with some.

var objects = [{id: 1,name: 'test1'}, {id: 2,name: 'test2'}, {id: 3,name: 'test3'}, {id: 4,name: 'test4'}],
arrayOfKeys = [3, 1, 4];

var result = objects.filter((x, i) => {
  if (arrayOfKeys.some(k => x.id === k)) {
    returntrue;
  }
})
console.log(result.map(x=>x.name));

Something even shorter! would be

var objects = [{id: 1,name: 'test1'}, {id: 2,name: 'test2'}, {id: 3,name: 'test3'}, {id: 4,name: 'test4'}],arrayOfKeys = [3, 1, 4];

var result = objects.filter((x, i) => arrayOfKeys.some(k => x.id === k));

console.log(result.map(x=>x.name));

Post a Comment for "Filter An Array Of Objects And Extract Its Property By Using An Array Of Keys"