简体   繁体   中英

Check if key exist in array by pushing values

Can someone tell me why everytime I want to check if a key is avalaible inside my array the result that I get is false ? See my example below

 var obj = new Array(); obj.push({ name: "test1", value: "10" }); obj.push({ name: "test2", value: "40" }); //var inobject = "name" in obj; // result: false //var inobject = "test1" in obj; // result: false //var inobject = "10" in obj; // result: false var inobject = "value" in obj; $('body').append("<p>"+ inobject + "</p>"); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

You are checking if "value" exists in the array and not in elements of your array. To correctly check if "value" exists in an element of the array you need to address obj[i] . Like this:

var obj = new Array();
obj.push({ name: "test1", value: "10" });
obj.push({ name: "test2", value: "40" });
var inobject = "value" in obj[0];
console.log(inobject);

Because "value" in obj isn't the way you check a value's existence in an array, and you have an array of objects, which means you have to check the existence against the array's elements not the array itself, this is how you do it :

 var obj = new Array(); obj.push({ name: "test1", value: "10" }); obj.push({ name: "test2", value: "40" }); var inobject = obj.some((a) => "value" in a); console.log(inobject); // true, means it's there 

If you want to get the elements that have the key "value", use :

 var obj = new Array(); obj.push({ name: "test1", value: "10" }); obj.push({ name: "test2", value: "40" }); obj.push({ name: "test2", AnotherKey: "60" }); var objects = obj.filter((a) => "value" in a); console.log(objects); // test1 and test2 

The problem is that you are trying to check if the key exists on the Array, rather than on the objects within the array, so as expected those keys do not match as they don't exist on the array.

If you are trying to check if any objects within an array has a specific key, then you can do this with a simple loop:

var found = false;
var search = "value";
for(var i = 0; i < obj.length; i++){
    if(search in obj[i]){
        found = true;
        break;
    }
}

Or separate it into a nice function:

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

var inobject = doesKeyExist(obj, "value");
$('body').append("<p>"+ inobject + "</p>");

If you want to find the value of a property, you can do this:

function doesValueExistForKey(var arr, var key, var search){
    for(var i = 0; i < obj.length; i++){
        if(key in obj[i] && obj[i][key] === search)
             return true;
    }
    return false;
}

var inobject = doesValueExistForKey(obj, "name", "test1");
$('body').append("<p>"+ inobject + "</p>");

You can only search for keys of the array or values like this:

 var obj = new Array(), el1, el2 obj.push(el1 = { name: "test1", value: "10" }); obj.push(el2 ={ name: "test2", value: "40" }); $('body').append("<p>check for key 1: "+ (1 in obj) + "</p>"); $('body').append("<p>check for element el1: "+ (obj.indexOf(el1) >= 0) + "</p>"); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

If you are searching an element inside the array that meets other criteria you have to do something like this:

 var obj = new Array(); obj.push({ name: "test1", value: "10" }); obj.push({ name: "test2", value: "40" }); // direct object access var inobject = obj.filter((e)=>{ return 'value' in e && e.value == 10}).length > 0; // deconstruct elements for better readability (WARNING: object deconstruction is not supported in all browsers yet!) var inobject2 = obj.filter(({name, value})=>{ return 'value' !=undefined && value == 10}).length > 0; $('body').append("<p>Search for element with value = 10: "+ inobject + "</p>"); $('body').append("<p>Search for element with value = 10: "+ inobject2 + "</p>"); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

If you want to find a key exist in any of the object, (first level) in a collection then instead of doing "value" in obj; you can do obj.some(e=> "value" in o);

 //name is obj but its actually a array var obj = new Array(); obj.push({ name: "test1", value: "10" }); obj.push({ name: "test2", value: "40" }); function checkForKey(list, key) { return list.some(e => key in e); } console.log('Key [name]:', checkForKey(obj, 'name')); console.log('Key [age]:', checkForKey(obj, 'age')); console.log('Key [value]:', checkForKey(obj, 'value')); 

If you are looking at any level, inside either an array or object recursively, then try this, (not much performance efficient but easy to manipulate)

 var obj = new Array(); obj.push({ name: "test1", value: "10" }); obj.push({ name: "test2", value: "40" }); function checkForKeyNested(list, key) { try { JSON.parse(JSON.stringify(list), function(k, v){ if(key===k) { flag=true; throw 0; } return v; }); } catch(ex) { return true;} return false; } console.log('Key [name]:', checkForKeyNested(obj, 'name')); console.log('Key [age]:', checkForKeyNested(obj, 'age')); console.log('Key [value]:', checkForKeyNested(obj, 'value')); 

You May try for this.

var obj = new Object();
obj.name='t1';
obj.value='t2';

obj.hasOwnProperty('value'); // Return true if exist otherwise false

The in operator checks for property key names of the object it is called on. You can use it on the objects you pushed into the array, or use it with the array indexes.

 // a little nano-sized test suite made on the fly :) const passed = document.getElementById('passed') const assert = test => { if (!test) throw 'invalid assertion' passed.innerText = +passed.innerText + 1 } // creates an Object that inherits from Array.prototype var obj = new Array() // Append an object {name, value} to the array // obj.push({ name: 'test1', value: 10 }) // Add a property to the array-object called value obj.value = 40 assert('name' in obj === false) assert('value' in obj === true) assert(0 in obj === true) assert('name' in obj[0] === true) 
 <p><span id='passed'>0</span> tests passed</p> 

You are working with an array of objects. Several ways to do this, but let's simply create a lookup and lookupAll function and use it: (they both return arrays of objects) the others return index and indexes array - changes if you sort. Note this works, even in very much ugly older browsers like IE6.

 // create a namespace for my functions var myApp = myApp || {}; myApp.arrayObj = { indexOf: function(myArray, searchTerm, property) { for (var i = 0; i < myArray.length; i++) { if (myArray[i][property] === searchTerm) return i; } return -1; }, indexAllOf: function(myArray, searchTerm, property) { var ai = []; for (var i = 0; i < myArray.length; i++) { if (myArray[i][property] === searchTerm) ai.push(i); } return ai; }, lookup: function(myArray, searchTerm, property, firstOnly) { var found = []; var i = myArray.length; while (i--) { if (myArray[i][property] === searchTerm) { found.push(myArray[i]); if (firstOnly) break; //if only the first } } return found; }, lookupAll: function(myArray, property, searchTerm) { return this.lookup(myArray, searchTerm, property, false); } }; var myobj = [{ name: "friend", value: "17" }];// better than new Array() myobj.push({ name: "test1", value: "10" }); myobj.push({ name: "test2", value: "40" }); console.log(myobj); // array of all matches var allones = myApp.arrayObj.lookupAll(myobj, "test1", "name"); console.log(allones.length);// 1 // returns array of 1 var firstone = myApp.arrayObj.lookup(myobj, "friend", "name",true); console.log(firstone[0].value);//17 

The in operator checks for keys . Your array has the following keys:

0,1

So

 0 in obj 

is true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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