I have an array of objects in a variable and I have id of the provider in a different variable. How do I get the name of the provider based on the id. how do I get the name based on the id. when I compare the id variable with with variable containing the array of objects.
Array of objects:
0: Object { id: "620d77165bd6857e3bdfed46", name: "provider 2", type: "TMS" } 1: Object { id: "620d771a5bd6857e3bdfed49", name: "provider 3", type: "Other" } 2: Object { id: "620d77205bd6857e3bdfed4c", name: "provider 4", type: "Load Board" } 3: Object { id: "62220e49c547d431a94c2aa8", name: "provider 5", type: "TMS" } 4: Object { id: "62221b86c547d431a94c2aba", name: "provider 6", type: "Load Board" } 5: Object { id: "6226887428359eb63456901a", name: "provider 1", type: "Load Board" } 6: Object { id: "62309b7d75a9fe3632ed9649", name: "asd", type: "TMS" } 7: Object { id: "62309b8375a9fe3632ed964f", name: "asdasdas", type: "Load Board" } 8: Object { id: "6230de7eb8432ab865c77a04", name: "asd provider 2", type: "Load Board" } 9: Object { id: "6230e05fb8432ab865c77a09", name: "adad", type: "Load Board" } 10: Object { id: "6230e091b8432ab865c77a10", name: "adada123123", type: "Load Board" } 11: Object { id: "6230e0e8b8432ab865c77a19", name: "asdasdasdadasdasda", type: "Load Board" } 12: Object { id: "6230e22db8432ab865c77a20", name: "adasd", type: "Load Board" } 13: Object { id: "6230e239b8432ab865c77a29", name: "adasd12312313123", type: "TMS" } 14: Object { id: "623366f8fc1ac7ff6f7bbd17", name: "asasasaaaaaaaaaaaa1111111111", type: "Load Board" } 15: Object { id: "6233670dfc1ac7ff6f7bbd25", name: "asasasaa1212111111", type: "Select a Type" } 16: Object { id: "62337769dac5619a6c6f56f9", name: "simpleProovider", type: "newTMS" } 17: Object { id: "6241a25e5bc31aec9152932f", name: "Uber Frieght", type: "Load Board" }
What i have tried so far.
let result = providerList.map(({ id }) => name); console.log(result);
Advertisement
Answer
You can use find
function.
const result = providerList.find((x) => x.id === yourId); const name = result? result.name : null;
Or you can get it with lodash
library.
const name = _.get(_.find(providerList, {id: yourId}), 'name');