简体   繁体   English

JavaScript:在 Object 数组中查找值

[英]JavaScript: Finding a value in an Object Array

I've got an array of objects defined like this:我有一个这样定义的对象数组:

var editionsObj = new Array();
function editionObject(name,description)
{
    this.name = name;
    this.description = description;
}

I need to search the editionsObj array for the existence of a variable in the name field.我需要在 editionsObj 数组中搜索名称字段中是否存在变量。 If no object in array has a name value equal to what I need, I'm going to insert it into the array.如果数组中没有 object 的名称值等于我需要的值,我将把它插入到数组中。 I've seen some examples in jQuery but wasn't able to get any to work.我在 jQuery 中看到了一些示例,但无法正常工作。

Thanks in advance!提前致谢!

Was able to solve this with code similar to the following:能够使用类似于以下的代码解决此问题:

var objCheck = null;
objCheck = jQuery.grep(editionsObj, function(n, i) {
     return n.name == currentEdition;
});
if ((objCheck == null) || (objCheck.length == 0))
{
     editionsCount++;
     editionsObj[editionsCount] = new editionObject(currentEdition,currentFamily,'');
}

Basically it performs a grep on the object array checking a certain index (name) for the value.基本上它在 object 数组上执行 grep ,检查某个索引(名称)的值。 If the value doesn't exist, then I perform the add.如果该值不存在,那么我执行添加。

Hope it helps someone else!希望它可以帮助别人!

I'm going to assume that each element of your array has only two properties.我将假设您的数组的每个元素只有两个属性。 If that's correct, then forget the idea of having named properties and just use a JS object:如果这是正确的,那么忘记命名属性的想法,只使用 JS object:

var editionsObj = {};
function addIfNotExists(name,description){
  if(!(name in editionsObj)) editionsObj[name] = description;
}

A simple for loop should suffice:一个简单for循环就足够了:

var nameToSearchFor = 'Bob',
    desc = 'whatever',
    alreadyExists = false;
for (var i = 0, il = editionsObj.length; i < il; i++) {
  if (editionsObj[i].name === nameToSearchFor) {
    alreadyExists = true;
    break;
  }
}
if (!alreadyExists) {
  editionsObj.push(new editionObject(nameToSearchFor, desc));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM