Technologies:
Tolerim
25 days ago
What is the process for obtaining a dictionary key from the value of another one in JavaScript?
I have been provided with an array, without any control over its structure:
myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}, etc.]
However, I need to extract the value of 'bar'
from an object in this array corresponding to a given id
of 45
. To achieve this, I can use JavaScript or jQuery.
Do you have any idea how I can accomplish this task?Answers(2)
Vogi
25 days ago
Verified Answer
Yes, you can use the find() method to get the object with the given id and then extract the value of foo property from it. Here's how you can do it:
const myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];
const obj = myArray.find(o => o.id === '45');
const value = obj.foo;
console.log(value); // Output: bar
Here, we first use the find() method to get the object with id equal to '45'. Then we extract the value of foo property from it and store it in the value variable. Finally, we log the value of value variable to the console.
I hope this helps! Let me know if you have any other questions.
Sources
Object.values() - JavaScript | MDN - Mozilla DeveloperExtract property value as array from array of objects in JavaScriptJavaScript Extract Elements From Array - Tuts Makeextract values from array of objects javascript - Askavyjavascript - From an array of objects, extract value of a property as ...javascript - Extract value from array of objects - Stack OverflowTolerim
25 days ago
You can accomplish this using JavaScript's built-in find() method. Here's an example code that shows how to get the value of foo for an object with id equal to 45:
const myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'},{'id':'99','foo':'baz'}];
const result = myArray.find(obj => obj.id === '45');
console.log(result.foo); // Output: 'bar'
If you prefer to use jQuery, you can use the $.grep() function to filter the array based on the id property and then get the value of foo for the first matched object:
const myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'},{'id':'99','foo':'baz'}];
const result = $.grep(myArray, function(obj){ return obj.id === '45'; });
console.log(result[0].foo); // Output: 'bar'