Getting an object's assigned variable name from a value in JavaScript [closed]

Solution 1:

Why don't you make an array out of your objects and search for your wanted index?

Just to give a few examples when we assume your object look like this:

const objects = [
    {name:"John", id:"0"},
    {name:"James", id:"1"},
    {name:"Jessica", id:"2"},
];

<Array>.find()

objects.find((e) => e.id === "1");

const objects = [
    {name:"John", id:"0"},
    {name:"James", id:"1"},
    {name:"Jessica", id:"2"},
];

const result = objects.find((e) => e.id === "1");
console.log(result);

<Array>.filter()

objects.filter((e) => e.id === "1")[0];

const objects = [
    {name:"John", id:"0"},
    {name:"James", id:"1"},
    {name:"Jessica", id:"2"},
];

const result = objects.filter((e) => e.id === "1")[0];
console.log(result);

<Array>.reduce()

objects.reduce((acc, curr) => (curr.id === "1") ? curr : acc);

const objects = [
    {name:"John", id:"0"},
    {name:"James", id:"1"},
    {name:"Jessica", id:"2"},
];

const result = objects.reduce((acc, curr) => (curr.id === "1") ? curr : acc);
console.log(result);

<Array>.some()

let result;
objects.some((e) => e.id === "1" && (result = e));

const objects = [
    {name:"John", id:"0"},
    {name:"James", id:"1"},
    {name:"Jessica", id:"2"},
];

let result;
objects.some((e) => e.id === "1" && (result = e));
console.log(result);

Solution 2:

Objects don't have names, and more than one variable or property can refer to the same object. So in the general case, no, you can't find "the" variable containing an object by an object property because there may be more than one (and because there isn't really a good way to find them).

If you put those objects in an array, you can easily find the object with id = "1":

const objects = [
    {name:"John", id:"0"},
    {name:"James", id:"1"},
    {name:"Jessica", id:"2"},
];
// To find it:
const result1 = objects.find(object => object.id === "1");
console.log(result1);
// Or more generally:
function findById(array, id) {
    return array.find(object => object.id === id);
}
const result2 = findById(objects, "1");
console.log(result2);

find loops through an array calling your callback, and returns the first object the callback returns a truthy value¹ for (or undefined if the callback never returns a truthy value). (There could, of course, be more than one, but find returns just the first.)


¹ "truthy value" - JavaScript has the concept of values that convert to true or false when used where a boolean is expected, The ones that convert to true are called "truthy," and the ones that convert to false are called "falsy." The falsy values are 0, NaN, null, undefined, "", and of course false (also document.all on browsers, for complex historical reasons). All other values are truthy.