nyphur
nyphur

Reputation: 2886

Using a value to compare against an array of objects to return a different value within that object?

I have an array of objects:

(7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}]

and an id value that I want to look for inside of this array of objects.

The id = "c2a6e78d2bc34cffb08d6e17a5631467"

then using, this id, I want to return to me the object that has the id matching the one I have. After that, I just simply want to get a different property of that object, like object.createdAt.

My question is: would it be possible to use .map over this array, and then use this id to return to me the one object that contains and matches this id? So far I've used map, and filter but maybe I'm using this the wrong way...

Upvotes: 1

Views: 54

Answers (2)

lealceldeiro
lealceldeiro

Reputation: 14968

would it be possible to use .map over this array, and then use this id to return to me the one object that contains and matches this id?

No, it would not be possible (or its usage wouldn't be the proper one) because map

creates a new array with the results of calling a provided function on every element in the calling array

In this case it would create an array with the properties createdAt instead of objects with all the properties (including the id which is necessary to be checked). So you could not pick up the correct object based on the id property.

Instead use find, which

returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned

Like this:

var obj = array.find(o => o.id === "c2a6e78d2bc34cffb08d6e17a5631467");

Now in obj you have the object with the id equals to c2a6e78d2bc34cffb08d6e17a5631467. You can check if the object is not undefined (it was found) and then access its properties as you wish.

console.log(obj ? obj.createdAt : "not found");

var array = [{
    id: "c2a6e78d2bc34cffb08d6e17a5631467",
    createdAt: '2017-01-02'
  },
  {
    id: "some-other-id",
    createdAt: '2017-01-03'
  },
  {
    id: "some-other-id-2",
    createdAt: '2017-01-03'
  },
];

var obj = array.find(o => o.id === "c2a6e78d2bc34cffb08d6e17a5631467");
console.log(obj ? obj.createdAt : "not found");

Upvotes: 3

John Ellmore
John Ellmore

Reputation: 2229

Use Array.find():

var myDesiredObject = myData.find(element => element.id == myDesiredId);

Upvotes: 5

Related Questions