开发者

Is there a more efficent way of selecting a particular object inside an array of objects

开发者 https://www.devze.com 2023-03-08 06:01 出处:网络
Given the following data structure var things = [{ \"name\": \"thing1\", \"sex\": \"male\"}, { \"name\": \"thing2\", \"sex\": \"female\"}];

Given the following data structure

var things = [{ "name": "thing1", "sex": "male"},
              { "name": "thing2", "sex": "female"}];

I would like to be able to search that array of objects and pull out a particular object.

I currently have the following code written

function selectElementByName (name) { 

  var returnObjec开发者_Python百科t;

  for (var i = 0; i < things.length; i++) {

    if (things[i].name === name) {

        returnObject = things[i];
    }
  } 


  if ( returnObject === undefined) { 
    console.log("Object not found");
  }

  return returnObject;
}

JsFiddle can be found here

Is there a more efficient way of doing this?


You can make an early exit when an object is found, so that you don't have to loop through the rest of the array:

function selectElementByName(name) { 
  for (var i = 0; i < things.length; i++) {
    if (things[i].name === name) {
      return things[i];
    }
  }
  console.log("Object not found");
}

(This will however change the behaviour if there are duplicates, so that it returns the first object found instead of the last.)


If the names are unique, you could use them as key and store the objects in an object instead of in an array:

var things = {
  "thing1": { "name": "thing1", "sex": "male"},
  "thing2": { "name": "thing2", "sex": "female"}
};

Then you wouldn't need to loop to find an object:

function selectElementByName(name) { 
  return things[name];
}

If you need the objects in an array, you could still create an index for searching if the array doesn't change so often:

var thingsNameIndex = {};
for (var i = 0; i < things.length; i++) {
  thingsNameIndex[things[i].name] = i;
}

Now you can use the index to find the object:

function selectElementByName(name) { 
  return things[thingsNameIndex[name]];
}

As you have to update or recreate the index as soon as the array changes, this would only be usedful if you do searches in the array much more often than you change the array.


In more recent versions of JavaScript:

var selectElementByName = function(name) {
    // This will fetch all items that match the filter
    // and place them in a new array
    var items = things.filter(function(item) {
        return item.name === name;
    });

    // If there isn't anything in the array, log the error and return.
    if (!items.length) {
        console.log("Object not found");
        return;
    }

    // Return the first matched element in the array.
    return items[0];
};


You can break once it's found at least:

for (var i = 0; i < things.length; i++) {
    if (things[i].name === name) {                        
        returnObject = things[i];
        break;
    }
} 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号