-1

I have an array of objects and I wanted to search through each object and check if the data matches a given value and I want to return the object out of the array and if it is not found then I have to return undefined.

This is what I have so far:

var data = [{
  id: 1,
  firstName: 'John',
  lastName: 'Smith'
}, {
  id: 2,
  firstName: 'Jane',
  lastName: 'Smith'
}, {
  id: 3,
  firstName: 'John',
  lastName: 'Doe'
}];
var asf[] = data[0];
return asf;

I'm trying to return the object if the condition in if else statement matches but it gives me error in returning array object.

I am also trying to use _.findwhere(data, pid) which is method in module of underscore can I use it to return the object out of array?

nponeccop
  • 13,527
  • 1
  • 44
  • 106
  • What do you mean "return object out of array". Do you want to remove it? – Carcigenicate Feb 11 '17 at 17:18
  • var findObjectWithThisValue = 3; var data = [{ id: 1, firstName: 'John', lastName: 'Smith' }, { id: 2, firstName: 'Jane', lastName: 'Smith' }, { id: 3, firstName: 'John', lastName: 'Doe' }]; function SearchObject(value) { var myObject = data.filter(function(obj) { return obj.id == findObjectWithThisValue }); if (myObject.length == 0) { return 'undefined'; } else { return myObject; } } SearchObject(findObjectWithThisValue); – Yogendra Paudyal Feb 11 '17 at 18:19
  • What if there are multiple matches? –  Feb 11 '17 at 18:29

3 Answers3

1

You can use Array.prototype.find(), like this:

var data = [{
  id: 1,
  firstName: 'John',
  lastName: 'Smith'
}, {
  id: 2,
  firstName: 'Jane',
  lastName: 'Smith'
}, {
  id: 3,
  firstName: 'John',
  lastName: 'Doe'
}];

data.find(x => {x.id === 1});

If you like to know more about arrays vist this link.

http://exploringjs.com/es6/ch_arrays.html

Asif Saeed
  • 1,985
  • 14
  • 24
0

I'm not sure if you want to return the object or remove the object so I'll show you how to do both as both are very simple to do.

This is a tidied version of your data:

// this is your data
var data = [{
  id: 1,
  firstName: 'John',
  lastName: 'Smith'
}, {
  id: 2,
  firstName: 'Jane',
  lastName: 'Smith'
}, {
  id: 3,
  firstName: 'John',
  lastName: 'Doe'
}];

This the loop you'll use to return the target object from the array:

// loop through the data array
for(var i = 0; i < data.length; i++) {
  // check if the current item is "John Smith"
  if(data[i].firstName == "John" && data[i].lastName == "Smith") {
    return data[i];
  }
  // continue with the loop if the current item is not "John Smith"
  continue;
}

This snippet does the exact same thing but without the continue:

// loop through the data array
for(var i = 0; i < data.length; i++) {
  // check if the current item is "John Smith"
  if(data[i].firstName == "John" && data[i].lastName == "Smith") {
    return data[i];
  }
}

This the loop you'll use to remove the target object from the array:

// loop through the data array
for(var i = 0; i < data.length; i++) {
  // check if the current item is "John Smith"
  if(data[i].firstName == "John" && data[i].lastName == "Smith") {
    delete data[i];
    // you can also use Array.prototype.splice() to remove an item from an array:
    // data.splice(i, 1);
  }
  // continue with the loop if the current item is not "John Smith"
  continue;
}

This snippet does the exact same thing but without the continue:

// loop through the data array
for(var i = 0; i < data.length; i++) {
  // check if the current item is "John Smith"
  if(data[i].firstName == "John" && data[i].lastName == "Smith") {
    delete data[i];
    // you can also use Array.prototype.splice() to remove an item from an array:
    // data.splice(i, 1);
  }
}

Use this snippet if you are using jQuery, instead of returning or deleting anything you can handle the object however you please inside the jQuery callback function.
In this case, I'll be using console.log(); as an example:

$.each(data, function(i, object) {
  if(object.firstName == "John" && object.lastName == "Smith") {
    console.log(object);
  }
});

Good luck and all the best.

  • When i return the object out of array do i need to make another array that will accept this incoming object as i want to manipulate further. Like var asf[]=function(data) – Kamran Saeed Feb 11 '17 at 17:32
  • @KamranSaeed No, you don't. For example where it says `console.log(object);` you can change it to specify the object to any function or manipulate it in any way you need. –  Feb 11 '17 at 17:34
  • What is the purpose of the `continue` statements? –  Feb 11 '17 at 17:37
  • @torazaburo To show the OP that the continue statement is optional and not required. –  Feb 11 '17 at 17:39
  • what if i want to search only on the basis of lastname. In that case it has to return two objects out of array. So how to do that. Because if i use return statement it returns on the first match. – Kamran Saeed Feb 11 '17 at 18:36
  • @KamranSaeed You would just remove the `object.firstName == "John" &&`. –  Feb 11 '17 at 19:10
0

Vanilla JS:

var findWhere = function(key,val,array) {
   var o;
   array.some(function(object) { return object[key] == val && (o = object); });
   return o;
};

var data = []; //your array
findWhere('id',1,data); //get the first object in the array where id = 1

EDIT

Here's a better one that actually takes a callback and can return just one element, or all matching elements:

var find = function(arr,cb,all) {
    var o;
    if(all) {
        return arr.filter(cb);
    }

    arr.some(function(object) { return cb(object) && (o = object); });
    return o;
};

var findAll = function(arr,cb) { return find(arr,cb,true); };

//return the first object in the data array where the id = 1
find(data,function(object) { return object.id == 1 });

//return all objects in the data array where name = 'John'
findAll(data,function(object) { return object.firstName = 'John'; });
Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100
  • This is just an awkward way of writing `find`. –  Feb 11 '17 at 17:38
  • An awkward way that has better browser support, yes – Adam Jenkins Feb 11 '17 at 18:20
  • @Adam Would you mind if I replaced the `find` poly-fill on my site with this? It's much simpler and easier to understand. –  Feb 11 '17 at 18:33
  • @Mango - sure, but the first example is very limited. See my edit, it takes a callback function (like the actual `Array.prototype.find` method and can easily be used to return just the first element, or all matching elements, which goes way beyond just finding an object in an array with a specific key-value pair. – Adam Jenkins Feb 11 '17 at 18:49
  • @Adam Thanks, mate! You really made my day. –  Feb 11 '17 at 19:08