Home > Software design >  Find element in map
Find element in map

Time:12-12

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?

CodePudding user response:

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')

CodePudding user response:

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);

CodePudding user response:

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)

CodePudding user response:

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

CodePudding user response:

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'))
  • Related