Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript map over array of obj with another array to get different key value

So I am not sure why I having such a difficult time with this, but I have an array of ids that I am trying to use to map over an array of objects to find the corresponding id but return the value from a different key.

i.e.: arr=[13, 1, 16]

arrObj= [{
          id: 1,
          name: "cat"
         }, {
          id: 10,
          name: "tiger", 
         }, {
          id: 3,
          name: "dog", 
         }, {
          id: 16,
          name: "bear", 
         }, {
          id: 8,
          name: "fish", 
         }, {
          id: 13,
          name: "goat", 
         }]

and I want it to return: ["goat", "cat", "bear"]

I have a nested map function that does this but returns undefined for the objects that do not have a corresponding ID. I could filter out the undefineds from the returned array, but it seems that there is a cleaner/more efficient way to do this.

What is the cleanest way to achieve this?

like image 636
CharStar Avatar asked Jun 22 '18 18:06

CharStar


2 Answers

You could use Array#map and search with Array#find for the corresponding object. Then take name as return value.

var arr = [13, 1, 16],
    arrObj = [{ id: 1, name: "cat" }, { id: 10, name: "tiger" }, { id: 3, name: "dog" }, { id: 16, name: "bear" }, { id: 8, name: "fish" }, { id: 13, name: "goat" }],
    result = arr.map(id => arrObj.find(o => o.id === id).name);

console.log(result);

For a lots of data, you could take a Map and build it by mapping key value pairs and then map the result of the map.

var arr = [13, 1, 16],
    arrObj = [{ id: 1, name: "cat" }, { id: 10, name: "tiger" }, { id: 3, name: "dog" }, { id: 16, name: "bear" }, { id: 8, name: "fish" }, { id: 13, name: "goat" }],
    result = arr.map(
        Map.prototype.get,
        new Map(arrObj.map(({ id, name }) => [id, name]))
    );

console.log(result);
like image 90
Nina Scholz Avatar answered Nov 14 '22 22:11

Nina Scholz


Try this:

var arr=[13, 1, 16];
var arrObj= [{
          id: 1,
          name: "cat"
         }, {
          id: 10,
          name: "tiger", 
         }, {
          id: 3,
          name: "dog", 
         }, {
          id: 16,
          name: "bear", 
         }, {
          id: 8,
          name: "fish", 
         }, {
          id: 13,
          name: "goat", 
         }];

var result = arr.map(id => arrObj.find(x => x.id == id)).map(x => x.name)
console.log(result);
// ["goat", "cat", "bear"]

.map() (from MDN web docs):

method creates a new array with the results of calling a provided function on every element in the calling array.

.find() (from MDN web docs):

method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.

like image 43
user2693928 Avatar answered Nov 14 '22 23:11

user2693928