2012-02-07 14 views

Respuesta

7

Dado que usted tiene una matriz llena de objetos, es necesario hacerlo así:

(ES3)

function lookup(name) { 
    for(var i = 0, len = arr.length; i < len; i++) { 
     if(arr[ i ].key === name) 
      return true; 
    } 
    return false; 
} 

if(!lookup('key1')) { 
    arr.push({ 
     key: 'key1', 
     value: 'z' 
    }); 
} 
18

Para que sea más fácil que usted debe almacenar sus datos de esta manera:

var map = { 
     "key1": "z", 
     "key2": "u" 
}; 

A continuación, puede hacer su cheque y si las llaves no entren en conflicto con cualquier propiedad existente sobre el objeto y usted don' Necesito valores nulos para que sea más fácil.

if (!map["key1"]) { 
    map["key1"] = "z"; 
} 

Si realmente necesita el objeto completo (el suyo es después de todo sólo un ejemplo), que almacenaría el objeto como el valor de la clave, no sólo almacenar los objetos de la matriz. Es decir, conviértalo en un mapa, no en una matriz.

1
var key; 
for(var i = 0; i < arr.length; i++) 
{ 
    if(arr[i].key == "key1") 
    { 
     key = arr[i]; 
     break; 
    } 
} 
if(typeof (key)=='undefined') //for if the value is 0 as int 
{ 
    key = { 
     key: "key1", value: "aaa" 
    }; 
    arr.push(key); 
} 
5

Se podría utilizar el ECMAScript 5 filter método para eliminar los elementos de la matriz si no pasan su prueba. Si la matriz resultante no tiene elementos, usted sabe que no había ninguno con su valor:

if(!arr.filter(function(elem) { 
    return elem.key === "key1"; 
}).length) { 
    arr.push({ key: "key1", value: "z" }); 
} 

Si quieres que funcione en los navegadores antiguos que tendría que utilizar una cuña para asegurarse Array.prototype.filter se define.

1

Puede verificar tanto las matrices como los objetos para ver si existe una clave de matriz o propiedad de objeto o no con esto. Es muy útil, y se usa de la misma manera para verificar ambos tipos.

/** 
* Check if an array key or object property exists 
* @key - what value to check for 
* @search - an array or object to check in 
*/ 
function key_exists(key, search) { 
    if (!search || (search.constructor !== Array && search.constructor !== Object)) { 
     return false; 
    } 
    for (var i = 0; i < search.length; i++) { 
     if (search[i] === key) { 
      return true; 
     } 
    } 
    return key in search; 
} 

Uso:

como una matriz

key_exists('jared', ['jared', 'williams']); //= true 

Como un objeto

key_exists('jared', {'jared': 'williams'}); //= true 
0

A continuación se presentan dos, más explícita, Versi ons de la respuesta aceptada de @ jAndy.

hice la primera versión para mí, así que pude entender la lógica mejor y añade lo siguiente:

si no existe la clave, incrementar la propiedad Count de la objeto emparejado, de lo contrario crear un nuevo objeto con un recuento de 1.

En la segunda versión, me di cuenta de que preferiría que mi variable de arrayOfObjects ser un object, de manera que después pude dirigirse específicamente a los valores en lugar de bucle sobre la matriz hasta que llegué un partido, y luego obtener el releva nt valor del objeto.Entonces esa versión usa un objeto en lugar de una matriz de objetos.

Version 01 - Una matriz de objetos

// based on: https://stackoverflow.com/a/9177103/1063287 
 

 
// the original array of objects 
 
var arrayofObjects = [{ 
 
    id: "CY01", 
 
    count: 1 
 
    }, 
 
    { 
 
    id: "CY33", 
 
    count: 5 
 
    }, 
 
    { 
 
    id: "CY55", 
 
    count: 8 
 
    } 
 
]; 
 

 
// show the array in the interface 
 
$(".before").text(JSON.stringify(arrayofObjects)); 
 

 
// define lookup function (must have access to arrayofObjects) 
 
function lookup(key_to_check) { 
 
    // for each object in the array of objects 
 
    for (var i = 0; i < arrayofObjects.length; i++) { 
 
    // if the object key matches the key to check 
 
    if (arrayofObjects[i]["id"] === key_to_check) { 
 
     // return true with index of matching object 
 
     var returnObject = {}; 
 
     returnObject["exists"] = true; 
 
     returnObject["index"] = i; 
 
     return returnObject; 
 
    } 
 
    } 
 
    // if the above loop has not already returned a value 
 
    // return false 
 
    var returnObject = {}; 
 
    returnObject["exists"] = false; 
 
    return returnObject; 
 
} 
 

 
// on click, check whether the key exists 
 
$(document).on("click", ".run", function() { 
 

 
    var key_to_check = $(".key_to_check").val(); 
 

 
    $(".checking").text(key_to_check); 
 

 
    var returnObject = lookup(key_to_check); 
 

 
    // if key to check doesn't exist add it 
 
    if (returnObject["exists"] === false) { 
 
    console.log("key doesn't exist, adding object"); 
 
    arrayofObjects.push({ 
 
     id: key_to_check, 
 
     count: 1 
 
    }); 
 
    } else if (returnObject["exists"] === true) { 
 
    // else if it does exists, increment the relevant counter 
 
    console.log("key does exist, incrementing object count value"); 
 
    var index = returnObject.index; 
 
    arrayofObjects[index].count += 1; 
 
    } 
 

 
    $(".after").text(JSON.stringify(arrayofObjects)); 
 
});
body { 
 
    font-family: arial; 
 
    font-size: 14px 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<p>enter an existing or non-existing key and click run.</p> 
 
<p>if existing, increment count, otherwise create new object with count of 1.</p> 
 

 
<input class="key_to_check"><button class="run">run</button> 
 

 
<br><br> 
 
<div>array of objects - before: <span class="before"></span> </div> 
 

 
<div>checking:<span class="checking"></span></div> 
 

 
<div>array of objects - after: <span class="after"></span></div>

Versión 02 - Un objeto

// based on: https://stackoverflow.com/a/9177103/1063287 
 

 
// the original object 
 
var myObject = { 
 
    "CY01": 1, 
 
    "CY33": 5, 
 
    "CY55": 8 
 
}; 
 

 
// show the object in the interface 
 
$(".before").text(JSON.stringify(myObject)); 
 

 
// define lookup function (must have access to myObject) 
 
function lookup(key_to_check) { 
 
    // for each property in the object 
 
    for (key in myObject) { 
 
    // if the key matches the key to check 
 
    if (key === key_to_check) { 
 
     // return true 
 
     return true 
 
    } 
 
    } 
 
    // if the above loop has not already returned a value 
 
    // return false 
 
    return false 
 
} 
 

 
// on click, check whether the key exists 
 
$(document).on("click", ".run", function() { 
 

 
    var key_to_check = $(".key_to_check").val(); 
 

 
    $(".checking").text(key_to_check); 
 

 
    var returnObject = lookup(key_to_check); 
 

 
    // if key to check doesn't exist add it 
 
    if (returnObject === false) { 
 
    console.log("key doesn't exist, adding object"); 
 
    myObject[key_to_check] = 1; 
 
    } else if (returnObject === true) { 
 
    // else if it does exists, increment the relevant counter 
 
    console.log("key does exist, incrementing object count value"); 
 
    myObject[key_to_check] += 1; 
 
    } 
 

 
    $(".after").text(JSON.stringify(myObject)); 
 
});
body { 
 
    font-family: arial; 
 
    font-size: 14px 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<p>enter an existing or non-existing key and click run.</p> 
 
<p>if existing, increment count, otherwise create new property with count of 1.</p> 
 

 
<input class="key_to_check"><button class="run">run</button> 
 

 
<br><br> 
 
<div>my object - before: <span class="before"></span> </div> 
 

 
<div>checking:<span class="checking"></span></div> 
 

 
<div>my object - after: <span class="after"></span></div>

Cuestiones relacionadas