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);
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 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>
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 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>");
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 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.
Related
I know we can match array values with indexOf in JavaScript. If it matches it wont return -1.
var test = [
1, 2, 3
]
// Returns 2
test.indexOf(3);
Is there a way to match objects? For example?
var test = [
{
name: 'Josh'
}
]
// Would ideally return 0, but of course it's -1.
test.indexOf({ name: 'Josh' });
Since the two objects are distinct (though perhaps equivalent), you can't use indexOf.
You can use findIndex with a callback, and handle the matching based on the properties you want. For instance, to match on all enumerable props:
var target = {name: 'Josh'};
var targetKeys = Object.keys(target);
var index = test.findIndex(function(entry) {
var keys = Object.keys(entry);
return keys.length == targetKeys.length && keys.every(function(key) {
return target.hasOwnProperty(key) && entry[key] === target[key];
});
});
Example:
var test = [
{
name: 'Josh'
}
];
var target = {name: 'Josh'};
var targetKeys = Object.keys(target);
var index = test.findIndex(function(entry) {
var keys = Object.keys(entry);
return keys.length == targetKeys.length && keys.every(function(key) {
return target.hasOwnProperty(key) && entry[key] === target[key];
});
});
console.log(index);
Note that findIndex was added in ES2015, but is fully polyfillable.
Nope, you can't and the explanation is simple. Despite you use the same object literal, two different objects are created. So test would have another reference for the mentioned object if you compare it with the reference you are looking for in indexOf.
This is kind of custom indexOf function. The code just iterates through the items in the object's array and finds the name property of each and then tests for the name you're looking for. Testing for 'Josh' returns 0 and testing for 'Kate' returns 1. Testing for 'Jim' returns -1.
var test = [
{
name: 'Josh'
},
{
name: 'Kate'
}
]
myIndexOf('Kate')
function myIndexOf(name) {
testName = name;
for (var i = 0; i < test.length; i++) {
if(test[i].hasOwnProperty('name')) {
if(test[i].name === testName) {
console.log('name: ' + test[i].name + ' index: ' + i);
return i;
}
}
}
return -1;
}
You can loop on array and then look for what you want
var test = [{ name: 'Josh' }]
const Myname = test.map((item) => { return item.name; }).indexOf("Josh")
I have a JavaScript array which I use jQuery to display values in a table
for (var i = 0; i < data.MyArray.length; i++) {
$('#my-table').append('<tr><td>' + data.MyArray[i].DisplayGroup + '</td><td>' + data.MyArray[i].Value + '%<td></tr>');
}
I would like to "group" the values based on DisplayGroup prior to displaying the values
So if my array contains
DisplayGroup: ABC Value: 5
DisplayGroup: DEF Value: 3
DisplayGroup: ABC Value: 6
DisplayGroup: GHI Value: 2
I would like to total the duplicate DisplayGroup entries (in this example ABC) so that I display
ABC 11
DEF 3
GHI 2
Is there a way to iterate through the array and create a new array to then use?
var array = [{
DisplayGroup: 'ABC',
Value: 5
}, {
DisplayGroup: 'DEF',
Value: 3
}, {
DisplayGroup: 'ABC',
Value: 6
}, {
DisplayGroup: 'GHI',
Value: 2
}];
Array.prototype.groupBy = function( key,value){
var newArray = []
var temp = []
this.filter((c,i,a)=> {
var ob = {}
if(temp.indexOf(c[key]) == -1){
ob[c[key]] = c[value] ;
newArray.push(ob)
temp.push(c[key]);
}
else{
newArray.filter((e)=> {
if(e[c[key]]){
e[c[key]] = e[c[key]] + c[value]
}
});
}
})
return newArray;
}
console.log(array.groupBy('DisplayGroup','Value'))
Is there a way to iterate through the array and create a new array to then use?
There's no need to create a new array, you can just use array reduction to create an object that contains all the data. The approach you can take is to iterate through the array and build the object by initializing not yet found values and incrementing the already initialized:
var convertedObject = arr.reduce(function(obj, item) {
var g = item.DisplayGroup;
var v = item.Value;
if (typeof obj[g] !== 'number') {
obj[g] = v; // initialize value that wasn't found yet
} else {
obj[g] += v; // update the value with the current increment
}
return obj;
}, {});
Then you can build the table using a similar loop to the one you have:
$.each(convertedObject, function(key, value) {
table.append('<tr><td>' + key + '</td><td>' + value + '<td></tr>');
});
Here's a running example:
var arr = [{
DisplayGroup: 'ABC',
Value: 5
}, {
DisplayGroup: 'DEF',
Value: 3
}, {
DisplayGroup: 'ABC',
Value: 6
}, {
DisplayGroup: 'GHI',
Value: 2
}];
// reducing into an object
var convertedObject = arr.reduce(function(obj, item) {
var g = item.DisplayGroup;
var v = item.Value;
if (typeof obj[g] !== 'number') {
obj[g] = v; // initialize value that wasn't found yet
} else {
obj[g] += v; // update the value with the current increment
}
return obj;
}, {});
var table = $('#table');
$.each(convertedObject, function(key, value) {
table.append('<tr><td>' + key + '</td><td>' + value + '<td></tr>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table">
</table>
If you need to, this is how you can convert this object into an array:
var convertedArray = Object.keys(convertedObject).map(function(key) {
var obj = {};
obj[key] = object[key];
return obj;
});
If I have an array like this:
var array1 =
[
{"phraseId":"abc",
"keyword":"bb",
"posId":1},
{"phraseId":"def",
"keyword":"bb",
"posId":1},
]
How can I find out that the object with phraseId of "def" has the 2nd position?
You could map your object and only return the target field, and then use the built in indexOf to get the position:
array1.map(item => item.phraseId).indexOf('def')
Use native JavaScript findIndex method.
var array1 = [{
"phraseId": "abc",
"keyword": "bb",
"posId": 1
}, {
"phraseId": "def",
"keyword": "bb",
"posId": 1
}, ];
var pos = array1.findIndex(function(v) {
// set your condition for finding object
return v.phraseId == 'def';
// add `1` since you want to count from `1`
}) + 1;
console.log("Position of the object " + pos);
For older browser check polyfill option.
With ES6 arrow function
var array1 = [{
"phraseId": "abc",
"keyword": "bb",
"posId": 1
}, {
"phraseId": "def",
"keyword": "bb",
"posId": 1
}, ];
var pos = array1.findIndex(v => v.phraseId == 'def') + 1;
console.log("Position of the object " + pos);
It works this way :
array1.forEach((elem, index) => {if (elem.phraseId === "def")
console.log("index = " + index);
});
Assuming that your key is know (that you know you are looking for a phraseId always) then you can simply iterate through the array with a normal for loop if you are using "traditional" JS, or with a forEach if you are using ES6. Here's the simple for implementation.
for (var i = 0; i < array1.length; i++ ){
if(array[i].phraseId === 'def') {
// we know "i" is the index, so do something...
}
}
To make it more generic so you can search any array for any key, make a function of it that returns the index:
function whatIndex (arr, key, val) {
for (var i = 0; i < arr.length; i++) {
if( arr[i][key] === val ) {
return i;
}
}
}
For example, I have:
var Data = [
{ id_list: 1, name: 'Nick', token: '312312' },
{ id_list: 2, name: 'John', token: '123123' },
]
Then, I want to sort/reverse this object by name, for example. And then I want to get something like this:
var Data = [
{ id_list: 2, name: 'John', token: '123123' },
{ id_list: 1, name: 'Nick', token: '312312' },
]
And now I want to know the index of the object with property name='John' to get the value of the property token.
How do I solve the problem?
Since the sort part is already answered. I'm just going to propose another elegant way to get the indexOf of a property in your array
Your example is:
var Data = [
{id_list:1, name:'Nick', token:'312312'},
{id_list:2, name:'John', token:'123123'}
]
You can do:
var index = Data.map(function(e) { return e.name; }).indexOf('Nick');
var Data = [{
id_list: 1,
name: 'Nick',
token: '312312'
},
{
id_list: 2,
name: 'John',
token: '123123'
}
]
var index = Data.map(function(e) {
return e.name;
}).indexOf('Nick');
console.log(index)
Array.prototype.map is not available on Internet Explorer 7 or Internet Explorer 8. ES5 Compatibility
And here it is with ES6 and arrow syntax, which is even simpler:
const index = Data.map(e => e.name).indexOf('Nick');
If you're fine with using ES6, arrays now have the findIndex function. Which means you can do something like this:
const index = Data.findIndex(item => item.name === 'John');
As the other answers suggest, looping through the array is probably the best way. But I would put it in its own function, and make it a little more abstract:
function findWithAttr(array, attr, value) {
for(var i = 0; i < array.length; i += 1) {
if(array[i][attr] === value) {
return i;
}
}
return -1;
}
var Data = [
{id_list: 2, name: 'John', token: '123123'},
{id_list: 1, name: 'Nick', token: '312312'}
];
With this, not only can you find which one contains 'John', but you can find which contains the token '312312':
findWithAttr(Data, 'name', 'John'); // returns 0
findWithAttr(Data, 'token', '312312'); // returns 1
findWithAttr(Data, 'id_list', '10'); // returns -1
The function returns -1 when not found, so it follows the same construct as Array.prototype.indexOf().
If you're having issues with Internet Explorer, you could use the map() function which is supported from 9.0 onward:
var index = Data.map(item => item.name).indexOf("Nick");
var index = Data.findIndex(item => item.name == "John")
Which is a simplified version of:
var index = Data.findIndex(function(item){ return item.name == "John"})
From mozilla.org:
The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.
Only way known to me is to loop through all array:
var index = -1;
for(var i=0; i<Data.length; i++)
if(Data[i].name === "John") {
index = i;
break;
}
Or case insensitive:
var index = -1;
for(var i=0; i<Data.length; i++)
if(Data[i].name.toLowerCase() === "john") {
index = i;
break;
}
On result variable index contain index of object or -1 if not found.
A prototypical way
(function(){
if (!Array.prototype.indexOfPropertyValue){
Array.prototype.indexOfPropertyValue = function(prop, value){
for (var index = 0; index < this.length; index++){
if (this[index][prop]){
if (this[index][prop] == value){
return index;
}
}
}
return -1;
}
}
})();
// Usage:
var Data = [
{id_list:1, name:'Nick', token:'312312'}, {id_list:2, name:'John', token:'123123'}];
Data.indexOfPropertyValue('name', 'John'); // Returns 1 (index of array);
Data.indexOfPropertyValue('name', 'Invalid name') // Returns -1 (no result);
var indexOfArray = Data.indexOfPropertyValue('name', 'John');
Data[indexOfArray] // Returns the desired object.
you can use filter method
const filteredData = data.filter(e => e.name !== 'john');
Just go through your array and find the position:
var i = 0;
for(var item in Data) {
if(Data[item].name == 'John')
break;
i++;
}
alert(i);
let indexOf = -1;
let theProperty = "value"
let searchFor = "something";
theArray.every(function (element, index) {
if (element[theProperty] === searchFor) {
indexOf = index;
return false;
}
return true;
});
collection.findIndex(item => item.value === 'smth') !== -1
You can use Array.sort using a custom function as a parameter to define your sorting mechanism.
In your example, it would give:
var Data = [
{id_list:1, name:'Nick',token:'312312'},{id_list:2,name:'John',token:'123123'}
]
Data.sort(function(a, b){
return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
});
alert("First name is : " + Data[0].name); // alerts 'John'
alert("Second name is : " + Data[1].name); // alerts 'Nick'
The sort function must return either -1 if a should come before b, 1 if a should come after b and 0 if both are equal. It's up to you to define the right logic in your sorting function to sort the array.
Missed the last part of your question where you want to know the index. You would have to loop through the array to find that as others have said.
This might be useful:
function showProps(obj, objName) {
var result = "";
for (var i in obj)
result += objName + "." + i + " = " + obj[i] + "\n";
return result;
}
I copied this from Working with objects.
Use a small workaround:
Create a new array with names as indexes. After that all searches will use indexes. So, only one loop. After that you don't need to loop through all elements!
var Data = [
{id_list:1, name:'Nick',token:'312312'},{id_list:2,name:'John',token:'123123'}
]
var searchArr = []
Data.forEach(function(one){
searchArr[one.name]=one;
})
console.log(searchArr['Nick'])
http://jsbin.com/xibala/1/edit
Live example.
I extended Chris Pickett's answer, because in my case I needed to search deeper than one attribute level:
function findWithAttr(array, attr, value) {
if (attr.indexOf('.') >= 0) {
var split = attr.split('.');
var attr1 = split[0];
var attr2 = split[1];
for(var i = 0; i < array.length; i += 1) {
if(array[i][attr1][attr2] === value) {
return i;
}
}
} else {
for(var i = 0; i < array.length; i += 1) {
if(array[i][attr] === value) {
return i;
}
}
};
};
You can pass 'attr1.attr2' into the function.
Use this:
Data.indexOf(_.find(Data, function(element) {
return element.name === 'John';
}));
It is assuming you are using Lodash or Underscore.js.
var fields = {
teste:
{
Acess:
{
Edit: true,
View: false
}
},
teste1:
{
Acess:
{
Edit: false,
View: false
}
}
};
console.log(find(fields,'teste'));
function find(fields,field) {
for(key in fields) {
if(key == field) {
return true;
}
}
return false;
}
If you have one Object with multiple objects inside, if you want know if some object are include on Master object, just use find(MasterObject, 'Object to Search'). This function will return the response if it exists or not (TRUE or FALSE). I hope to help with this - can see the example on JSFiddle.
If you want to get the value of the property token then you can also try this:
let data=[
{ id_list: 1, name: 'Nick', token: '312312' },
{ id_list: 2, name: 'John', token: '123123' },
]
let resultingToken = data[_.findKey(data,['name','John'])].token
where _.findKey is a Lodash function.
You can use findIndex in Lodash library.
Example:
var users = [
{ 'user': 'barney', 'active': false },
{ 'user': 'fred', 'active': false },
{ 'user': 'pebbles', 'active': true }
];
_.findIndex(users, function(o) { return o.user == 'barney'; });
// => 0
// The `_.matches` iteratee shorthand.
_.findIndex(users, { 'user': 'fred', 'active': false });
// => 1
// The `_.matchesProperty` iteratee shorthand.
_.findIndex(users, ['active', false]);
// => 0
// The `_.property` iteratee shorthand.
_.findIndex(users, 'active');
// => 2
Alternatively to German Attanasio Ruiz's answer, you can eliminate the second loop by using Array.reduce() instead of Array.map();
var Data = [
{ name: 'hypno7oad' }
]
var indexOfTarget = Data.reduce(function (indexOfTarget, element, currentIndex) {
return (element.name === 'hypno7oad') ? currentIndex : indexOfTarget;
}, -1);
Maybe the Object.keys, Object.entries, and Object.values methods might help.
Using Underscore.js:
var index = _.indexOf(_.pluck(item , 'name'), 'Nick');
I have the following array
var countries = {};
countries.results = [
{id:'AF',name:'Afghanistan'},
{id:'AL',name:'Albania'},
{id:'DZ',name:'Algeria'}
];
How can I remove an item from this array using its name or id ?
Thank you
Created a handy function for this..
function findAndRemove(array, property, value) {
array.forEach(function(result, index) {
if(result[property] === value) {
//Remove from array
array.splice(index, 1);
}
});
}
//Checks countries.result for an object with a property of 'id' whose value is 'AF'
//Then removes it ;p
findAndRemove(countries.results, 'id', 'AF');
Array.prototype.removeValue = function(name, value){
var array = $.map(this, function(v,i){
return v[name] === value ? null : v;
});
this.length = 0; //clear original array
this.push.apply(this, array); //push all elements except the one we want to delete
}
countries.results.removeValue('name', 'Albania');
Try this:
var COUNTRY_ID = 'AL';
countries.results =
countries.results.filter(function(el){ return el.id != COUNTRY_ID; });
Try this.(IE8+)
//Define function
function removeJsonAttrs(json,attrs){
return JSON.parse(JSON.stringify(json,function(k,v){
return attrs.indexOf(k)!==-1 ? undefined: v;
}));}
//use object
var countries = {};
countries.results = [
{id:'AF',name:'Afghanistan'},
{id:'AL',name:'Albania'},
{id:'DZ',name:'Algeria'}
];
countries = removeJsonAttrs(countries,["name"]);
//use array
var arr = [
{id:'AF',name:'Afghanistan'},
{id:'AL',name:'Albania'},
{id:'DZ',name:'Algeria'}
];
arr = removeJsonAttrs(arr,["name"]);
You can delete by 1 or more properties:
//Delets an json object from array by given object properties.
//Exp. someJasonCollection.deleteWhereMatches({ l: 1039, v: '3' }); ->
//removes all items with property l=1039 and property v='3'.
Array.prototype.deleteWhereMatches = function (matchObj) {
var indexes = this.findIndexes(matchObj).sort(function (a, b) { return b > a; });
var deleted = 0;
for (var i = 0, count = indexes.length; i < count; i++) {
this.splice(indexes[i], 1);
deleted++;
}
return deleted;
}
you can use delete operator to delete property by it's name
delete objectExpression.property
or iterate through the object and find the value you need and delete it:
for(prop in Obj){
if(Obj.hasOwnProperty(prop)){
if(Obj[prop] === 'myValue'){
delete Obj[prop];
}
}
}
This that only requires javascript and appears a little more readable than other answers.
(I assume when you write 'value' you mean 'id')
//your code
var countries = {};
countries.results = [
{id:'AF',name:'Afghanistan'},
{id:'AL',name:'Albania'},
{id:'DZ',name:'Algeria'}
];
// solution:
//function to remove a value from the json array
function removeItem(obj, prop, val) {
var c, found=false;
for(c in obj) {
if(obj[c][prop] == val) {
found=true;
break;
}
}
if(found){
delete obj[c];
}
}
//example: call the 'remove' function to remove an item by id.
removeItem(countries.results,'id','AF');
//example2: call the 'remove' function to remove an item by name.
removeItem(countries.results,'name','Albania');
// print our result to console to check it works !
for(c in countries.results) {
console.log(countries.results[c].id);
}
it worked for me..
countries.results= $.grep(countries.results, function (e) {
if(e.id!= currentID) {
return true;
}
});
You can do it with _.pullAllBy.
var countries = {};
countries.results = [
{id:'AF',name:'Afghanistan'},
{id:'AL',name:'Albania'},
{id:'DZ',name:'Algeria'}
];
// Remove element by id
_.pullAllBy(countries.results , [{ 'id': 'AL' }], 'id');
// Remove element by name
// _.pullAllBy(countries.results , [{ 'name': 'Albania' }], 'name');
console.log(countries);
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
Maybe this is helpful, too.
for (var i = countries.length - 1; i--;) {
if (countries[i]['id'] === 'AF' || countries[i]['name'] === 'Algeria'{
countries.splice(i, 1);
}
}
The accepted answer is problematic as it attaches a function to the Array prototype. That function will show up whenever you run thru the array using a for loop:
for (var key in yourArray) {
console.log(yourArray[key]);
}
One of the values that will show up will be the function. The only acceptable way to extend base prototypes (although it is generally discouraged as it pollutes the global space) is to use the .defineProperty method:
Object.defineProperty(Object.prototype, "removeValue", {
value: function (val) {
for (var i = 0; i < this.length; i++) {
if (this[i] === val) {
this.splice(i, 1);
i--;
}
}
return this;
},
writable: true,
configurable: true,
enumerable: false
});