Say I have this array:
var myArray = [
{
"name": "item 1",
"id": 123
},{
"name": "item 2",
"id": 456
}
];
What would be the proper way to get an item based on the id property? With this example, say I know I want the item for which item.id == 456.
I don't want jquery answers.
Try this:
var item = myArray.filter(function(item) { return item.id === 456; })[0];
You can implement a search function like below:
function searchArray(id) {
for(var i = 0; i < myArray.length; i++) {
if(myArray[i].id == id) {
return myArray[i];
}
}
console.log(id + ' not found');
}
for ( var index = 0; index < myArray.length; index++ ) {
if ( myArray[index].id == 456 )
//Item found
}
try
for (var i in myArray) {
if(myArray[i].id == 456) {
return myArray[i];
}
}
Related
I have to compare two values. Both values came from different loops.
if the value is an exact match, I push the array differently.
As you can see in the code. I cant use an "else" after the "if" function because it will literate till the loop stop. I would have multiple pushes.
If I add the array.push after the loop there will be 2 pushes.
for (var prop in obj) {
var array = []
for (var item in obj[prop]) {
for (var i = 0; i < doctyp88.length; i += 1) {
var doctyp88ID = doctyp88[i]._id;
var doctyp88name = doctyp88[i]._source['88_name'];
if (item == doctyp88ID) {
array.push({
"name": item,
"count": obj[prop][item],
"archivname": doctyp88name,
});
}
}
array.push({
"name": item,
"count": obj[prop][item],
});
}
}
What is the best way to avoid my problem?
for (var prop in obj) {
var array = []
for (var item in obj[prop]) {
const newObj = {
"name": item,
}
for (var i = 0; i < doctyp88.length; i += 1) {
var doctyp88ID = doctyp88[i]._id;
var doctyp88name = doctyp88[i]._source['88_name'];
newObj.count= obj[prop][item],
if (item == doctyp88ID) {
newObj.archivname = doctyp88name
}
}
array.push(newObj);
}
}
If I understood your question correctly you could use break [label]; statement to exit from nested loop and skip more pushes but don't exit outside for like this:
loop_1:
for (var prop in obj) {
var array = []
loop_2:
for (var item in obj[prop]) {
loop_3:
for (var i = 0; i < doctyp88.length; i += 1) {
var doctyp88ID = doctyp88[i]._id;
var doctyp88name = doctyp88[i]._source['88_name'];
if (item == doctyp88ID) {
array.push({
"name": item,
"count": obj[prop][item],
"archivname": doctyp88name,
});
break loop_2;
}
}
array.push({
"name": item,
"count": obj[prop][item],
});
}
}
I need search in an array of JSON objects if a key with especific id value exists. If exists, return it, if not return -1 or whatever
var array = [{'id': 1, 'name': 'xxx'},
{'id': 2, 'name': 'yyy'},
{'id': 3, 'name': 'zzz'}];
var searchValue --> id==1
should be something like this?
function search_array(array,valuetofind) {
if array.indexof({'id': valuetofind}) != -1 {
return array[array.indexof({'id': valuetofind})]
} else {
return {'id': -1}
}
}
This returns the object if a match exists and -1 if there's no match.
function search_array(array,valuetofind) {
for (i = 0; i < array.length; i++) {
if (array[i]['id'] === valuetofind) {
return array[i];
}
}
return -1;
}
If you simply need to make sure the id exists try this:
function search_array(array, valuetofind) {
var exists = false;
for(i=0;i<array.length;i++) {
if(array[i].id == valuetofind) {
exists = true;
}
}
return exists;
}
My method may be a little long winded cycling through each part but i checked and it works
search_array(array, 4) [False]
search_array(array, 1) [True]
try this
search(nameKey, myArray){
for (var i=0; i < myArray.length; i++) {
if (myArray[i].name === nameKey) {
return myArray[i];
}
}
}
var array = [
{ name:"string 1", value:"this", other: "that" },
{ name:"string 2", value:"this", other: "that" }
];
var resultObject = search("string 1", array);
I know given a single key (for example, if I know the object.name = 'Sam') using:
var index = array.map(function(el) {return el.name}).indexOf('Sam');
I can get the index of the array element with object.name = 'Sam'
However say I have several elements with object.name ='Sam' in the array, but now I know know the object.name, object.age and object.size - is it possible to adapt the above code to get the index but also checking against object.age and object.size?
Assuming you have the values in variables such as name, age and size as you mentioned in comments, You can use a function like:
function findInArray(arr) {
for (var i = 0; i < arr.length; i++) {
var el = arr[i];
if (el.name == name && el.age == age && el.size == size)
return i;
}
return -1;
};
Which will return the index of object in array if match is found, and -1 otherwise...
var data = [{
name: "Sis",
age: "17",
size: "10"
}, {
name: "Sam",
age: "17",
size: "10"
}, {
name: "Som",
age: "17",
size: "10"
}],
name = "Sam",
age = "17",
size = "10";
function findInArray(arr) {
for (var i = 0; i < arr.length; i++) {
var el = arr[i];
if (el.name == name && el.age == age && el.size == size)
return i;
}
return -1;
};
console.log(findInArray(data));
If you're using the awesome underscore library there's a _.findWhere function.
var sam21 = _.findWhere(people, {
name: 'Sam',
age: 21
});
if you want something without a whole other library you can use .filter.
var sam21 = people.filter(function(person) {
return person.age === 21 && person.name === 'Sam';
});
I just noticed you're looking for the index. This answer can be useful: https://stackoverflow.com/a/12356923/191226
You could use a function like this one
indexOfObjectArray = function(array, keyvalues) {
for (var i = 0; i < array.length; i++) {
var trueCount = 0;
for (var j = 0; j < keyvalues.length; j++) {
if (array[i][keyvalues[j]['key']] == keyvalues[j]['value']) {
trueCount++;
}
}
if (trueCount === keyvalues.length) return i;
}
return -1; }
and use it like that for example:
var yourArray = [{id: 10, group: 20},...];
var keyvalues = [
{ 'key': 'id', 'value': 10 },
{ 'key': 'group', 'value': 20 }];
var index = indexOfObjectArray(yourArray, keyvalues );
This function will return the index of an object that has id = 10 and group = 20
I have an object containing a bunch of similar objects. I would like to get the count of the object only for those where a object property (status) is of a given value (true). For instance, the count of the below object is 3.
{
6:{"name":"Mary", "status":true},
2:{"name":"Mike", "status":true},
1:{"name":"John", "status":false},
4:{"name":"Mark", "status":true},
5:{"name":"Jane", "status":false}
}
Thanks
I recognize you are iterating over an object, not an array, but since the others provide solutions for arrays I recon a solution with array.reduce is in place. Works in most modern browsers (IE9+)
var myArray = [
{"name":"Mary", "status":true},
{"name":"Mike", "status":true},
{"name":"John", "status":false},
{"name":"Mark", "status":true},
{"name":"Jane", "status":false}
];
var result = myArray.reduce(function(previousValue, currentObject){
return previousValue + (currentObject.status ? 1: 0);
}, 0);
Specifically:
var i = 0;
var count = 0;
while (i < array.length) {
if (array[i]['status'] == true) count += 1;
i += 1;
}
More generally, you can use some functional programming:
function count_matches(array, func) {
var i = 0;
var count = 0;
while (i < array.length) {
if (func(array[i])) count += 1;
i += 1;
}
return count;
}
function status_true(obj) {
return obj['status'] == true;
}
count_matches(array, status_true);
The above snippets do the same thing, but the latter is more flexible/potentially neater.
just loop over the array and count how many times the status property is true.
var count = 0;
for (var i = 0; i < yourArray.length; i++){
var current = yourArray[i];
if (current.status) count++
}
LinqJs would work (might be too much for the simple example posted in the question) -
http://linqjs.codeplex.com/
var jsonArray = [
{ "user": { "id": 100, "screen_name": "d_linq" }, "text": "to objects" },
{ "user": { "id": 130, "screen_name": "c_bill" }, "text": "g" },
{ "user": { "id": 155, "screen_name": "b_mskk" }, "text": "kabushiki kaisha" },
{ "user": { "id": 301, "screen_name": "a_xbox" }, "text": "halo reach" }]
// ["b_mskk:kabushiki kaisha", "c_bill:g", "d_linq:to objects"]
var queryResult = Enumerable.From(jsonArray)
.Where(function (x) { return x.user.id < 200 })
.OrderBy(function (x) { return x.user.screen_name })
.Select(function (x) { return x.user.screen_name + ':' + x.text })
.ToArray();
// shortcut! string lambda selector
var queryResult2 = Enumerable.From(jsonArray)
.Where("$.user.id < 200")
.OrderBy("$.user.screen_name")
.Select("$.user.screen_name + ':' + $.text")
.ToArray();
var obj = {
6:{"name":"Mary", "status":true},
2:{"name":"Mike", "status":true},
1:{"name":"John", "status":false},
4:{"name":"Mark", "status":true},
5:{"name":"Jane", "status":false}
};
var count = 0;
for (var prop in obj) {
if(obj[prop].status === true){
count += 1;
}
}
console.log("Output: "+count);
$("#debug").text("Output: "+count);
live demo http://jsbin.com/uwucid/2/edit
I have this JS object:
{
"data": {
"nid": [{
"cid": "32",
"uid": "780",
"comment": "text"
}]
},
"request_status": "found"
}
how can I loop through these items to get comment value ("comment":"text")?
You don't really need to loop to get it. Just do...
var obj = {"data":{"nid":[{"cid":"32","uid":"780","comment":"text"}]},"request_status":"found"};
var text = obj.data.nid[0].comment;
Or if there are several, you can use forEach...
obj.data.nid.forEach(function(val,i) {
alert( val.comment );
});
Or a traditional for loop...
for( var i = 0; i < obj.data.nid.length; i++ ) {
alert( obj.data.nid[i].comment );
}
Or if you want to build an Array, use map...
var arr = obj.data.nid.map(function(val,i) {
return val.comment;
});
Or again a traditional for loop...
var arr = []
for( var i = 0; i < obj.data.nid.length; i++ ) {
arr.push( obj.data.nid[i].comment );
}
Given:
var obj = {
"data": {
"nid": [{
"cid": "32",
"uid": "780",
"comment": "text"
}]
},
"request_status": "found"
};
The direct way to retrieve the comment is:
obj["data"]["nid"][0]["comment"]
// or
obj.data.nid[0].comment
As far as "looping" through the items to get the value, I'm not sure how a loop makes sense. Are you saying you might not know the structure of the object but you know it will have a "comment" field in there somewhere?
The "nid" array only has one item in it - if this was just a sample but really you'll have an array with more values you can loop through that array:
var nid = obj["data"]["nid"], // get a direct reference to the array to save
i; // repeating obj.data.nid everywhere
for (i=0; i < nid.length; i++) {
// do something with the comment in the current item
console.log(nid[i]["comment"]);
}
If you're just referring to that specific object (or if every object you are working with follows that same pattern), then you can just access the value directly:
var theObj = {"data":{"nid":[{"cid":"32","uid":"780","comment":"text"}]},"request_status":"found"};
alert(theObj.data.nid[0].comment);
If you want to do something iterative, then perhaps try this:
var theObj = {"data":{"nid":[{"cid":"32","uid":"780","comment":"text"}]},"request_status":"found"};
for (var index = 0; index < theObj.data.nid.length; index++) {
var item = theObj.data.nid[index];
if (item.comment) {
alert(item.comment);
}
}
Or if you really want to do the entire thing iteratively:
window.searchObj = function(theObj) {
if (theObj.comment) {
alert(theObj.comment);
}
if (theObj instanceof Array) {
searchArray (theObj);
}
else if (theObj instanceof Object) {
for (var key in theObj) {
searchObj(theObj[key]);
}
}
};
window.searchArray = function(theArray) {
for (var index = 0; index < theArray.length; index++) {
var item = theArray[index];
searchObj(item);
}
};
var theObj = {"data":{"nid":[{"cid":"32","uid":"780","comment":"text"}]},"request_status":"found"};
searchObj(theObj);