1

I have a map of objects:

"0": {
    key: 'id',
    value: {
        name: "eval"
        // other variables
    }
},
"1": {
    key: 'id',
    value: {
        name: "help"
        // other variables
    }
} // and so on

I need to find an element in map that's name variable is eqaul to "eval". What's the easiest way to do this?

Leau
  • 1,072
  • 5
  • 19

5 Answers5

2

If "map" is an array

let arr = [{key:'id', value:{ name:'eval' }}]
let item = arr.find(el => el.value.name == 'eval')

If "map" is an object

let obj = {0:{key:'id', value:{ name:'eval' }}}
let item = Object.values(obj).find(el => el.value.name == 'eval')
Spankied
  • 1,626
  • 13
  • 21
1

Use <Array>.from to convert map values to array and after filter what you want.

const map = new Map();

map.set(0, {
  key: 'id',
    value: {
      name: "eval"
    }
});

map.set(1, {
  key: 'id',
    value: {
      name: "help"
    }
});

const result = Array.from(map.values())
  .filter(x => x.value.name === 'eval')[0];
  
console.log(result);
Leau
  • 1,072
  • 5
  • 19
0

The good old forEach Loop can do it too.

const data = [{
    key: 'id',
    value: {
        name: "eval"
        // other variables
    }
},
{
    key: 'id',
    value: {
        name: "help"
        // other variables
    }
}]

let res = [];
data.forEach((el) => {
  if (el.value.name === "eval") {
    res.push(el);
  }  
})

console.log(res)
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
0

You can do this

const tmp = {
  "0": {
    key: "id",
    value: {
      name: "eval"
      // other variables
    }
  },
  "1": {
    key: "id",
    value: {
      name: "eval"
      // other variables
    }
  }
};

function findEval(obj, target) {
    const elem = Object.keys(obj).filter(key => tmp[key].value.name === target);
    return elem.map(e => obj[e]);
}
console.log(findEval(tmp, 'eval'))


but better use lodash Find property by name in a deep object

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 12 '21 at 00:05
0

simple and best solution

const tmp = {
  "0": {
    key: "id",
    value: {
      name: "eval"
      // other variables
    }
  },
  "1": {
    key: "id",
    value: {
      name: "eval"
      // other variables
    }
  }
};

function findEval(obj, target) {
    for (var i=0; i < Object.keys(obj).length; i++) {
        if (obj[i].value.name === target) {
            return obj[i].value.name;
        }
    }
}
console.log(findEval(tmp, 'eval'))
Waleed Muaz
  • 737
  • 6
  • 17