Check for a value in a JSON object - javascript

I need to find out if an id occurs in my JSON object, for example:
{
"requested": "2009-07-25T14:12:25+01:00",
"channels": [
{"id": 1, "name": "General", "created": "2009-07-25 14:00:02"}
]
}
Specifically I need to check if my id (say, 2) occurs in channels.i.id. How can this be done?

Try this:
var id = 2,
found = false;
for (var i=0; i<channels.length; i++) {
if (channels[i].id == id) {
found = true;
break;
}
}

Or more succinctly and probably faster :
var id = 2;
for (var found, i = channels.length; i && !(found = channels[--i].id === id);)
;

Related

remove array element using javascript

I am new to javascript & jquery, Need to remove an element from the below array structure
[{
"tag": "tag1",
"description": "description1"
}, {
"tag": "tag2",
"description": "description2"
}, {
"tag": "tag3",
"description": "description3"
}]
The element to be removed is known {"tag":"tag2", "description":"description2"}.
How can i find this element and remove from the array.
Please find the code which i am using to remove an element
var actionDic = [];
actionDic.push({
description: desc,
tag: tag
});
The actionDic array is populated as user enter text in textinput and selects 'add' option.
var deleterow = {
tag: "tag2",
description: "description2"
};
var index = $.inArray(deleterow, actionDic);
if (index != -1) {
actionDic.splice(index, 1);
}
The correct index is not obtained. Kindly let me know what wrong is in the code.
Thanks.
Since the comparison between the item to remove and each element in actionDic isn't trivial, you could use jQuery.grep():
actionDic = jQuery.grep(actionDic, function(elem) {
return elem.tag == deleterow.tag && elem.description == deleterow.description;
}, true);
Demo
It performs a search using a custom search function and returns the array elements that didn't match. The result replaces the previous value of actionDic and effectively removed that one item.
Update
Unfortunately, this method could be considered heavy because a new array gets created at each invocation; both in terms of what jQuery can do and standard JavaScript functionality, this particular feature is lacking. ECMAScript 6 will have the Array.prototype.find() method that will do the job of finding the index in an array (with which you can perform the splice).
You can of course write one yourself too:
(function($) {
$.find = function(arr, fn) {
for (var i = 0, len = arr.length; i < len; ++i) {
if (fn(arr[i], i, arr)) {
return i;
}
}
return -1;
};
}(jQuery));
var index = $.find(actionDic, function(elem) {
return elem.tag == deleterow.tag && elem.description == deleterow.description;
});
if (index != -1) {
actionDic.splice(index, 1);
}
Demo
I've implemented an indexOfObject method of Array prototype in one of my projects. It searches for an index of object by the given property name and value. Here it is:
Array.prototype.indexOfObject = function(searchTerm, property) {
for (var i = 0, l = this.length; i < l; i++) {
if (this[i][property] === searchTerm) {
return i;
}
}
return -1;
};
You can use this method to find the index of your object using a unique property. In your case you can use it like this:
var arr = [{
"tag": "tag1",
"description": "description1"
}, {
"tag": "tag2",
"description": "description2"
}, {
"tag": "tag3",
"description": "description3"
}], deleteObject = {
tag: "tag2",
description: "description2"
};
var index = arr.indexOfObject(deleteObject.tag, 'tag');
Then you can use that index to remove the object from the array:
if (index > -1) {
arr.splice(index, 1);
}
Here is the working example in JSFiddle.
var actionDic = [{
"tag": "tag1",
"description": "description1"
}, {
"tag": "tag2",
"description": "description2"
}, {
"tag": "tag3",
"description": "description3"
}]
var element = {"tag":"tag2", "description":"description2"}
for(var i=0;i<actionDic.length;i++) {
var found = false;
for(each in actionDic[i]) {
if(actionDic[i][each] == element[each]) {
found = true
} else {
found = false;
break;
}
}
if(found) {
actionDic.splice(i,1);
found=false;
}
}
This gets your inner array objects:
for (var x = 0; x < actionDic.length; x++){
var arrayItem = actionDic[x];
if (arrayItem["tag"] == "tag2"){
alert(arrayItem["description"]);
}
}
Working fiddle: http://jsfiddle.net/4khjp/
You can use underscore.js which contains many useful helpers for Objects, Arrays etc.
Removing array element:
array = _.reject(array, function(item) {
return item.tag == 'tag2'; // <- if tag is unique to whole array
});

javascript increment name of variable

I get an object with partial results of match from database.
[Object { home1=4, away1=3, home2=4, away2=5, home3=6, away3=7, home4=6, away4=5, home5=3, away5=6}]
home1 it's a result of first part of home team,
away1 -> away team, home2 it's a result of second part of home team... etc etc
data in my case is each row, which i get from database.
In rows i have td with class: home1, home2, home3, away1, away2 and there are values of corresponding part of match.
I want to check if value is equal to what I got from database.
Something like this
if ($('.home1') === data[index].home1;
if($('.away2') === data[index].away2;
there should be some loop. I have no idea how to do this, I thought about an array
var array = [
{
home1: data[index].home1,
away1: data[index].away1
},
{
home2: data[index].home2,
away2: data[index].away2
},
{
home3: data[index].home3,
away3: data[index].away3
},
{
home4: data[index].home4,
away4: data[index].away4
},
{
home5: data[index].home5,
away5: data[index].away5
}
]
and then for loop:
for(var X=0; X<5;X++){
homeX == data[index].homeX
}
How can I increment name of variable by eval function? or is there any other solution? I'm very confused.
You can access object properties using operator []:
for(var i=0; i<array.length; i++)
{
var item = array[i];
var homePropertyName = 'home' + (i+1);
//now you can access homeX property of item using item[homePropertyName]
//e.g. item[homePropertyName] = data[index][homePropertyName]
}
Maybe you should use a little different structure which might fit your needs better, like this:
array = [
0: array [
"home": "Text for home",
"away": "Text for away"
],
1: array [
"home": "",
"away": ""
]
// More sub-arrays here
];
You can also initialize it with a for loop:
var array = new Array();
var i;
for (i = 0; i < 4; i++) {
array[i] = [
"home": "",
"away": ""
];
}
Or like this:
array[0]["home"] = "Text for home";
array[0]["away"] = "Text for away";
You can use this structure for the data-array also, and then use a for-loop to go through them both (like if you wish to find an element):
var result = NULL;
for (i = 0; i < array.length; i++) {
if ( (array[i]["home"] == data[index]["home"]) &&
(array[i]["away"] == data[index]["away"])
) {
// Found matching home and away
result = array[i];
break;
}
}
if (result != NULL) {
alert("Found match: " + result["home"] + " - " + result["away"]);
}
else {
alert("No match");
}
PS: Code is not tested, let me know if something is wrong.
you can access global properties in browser via window object like this (fiddle):
value1 = "ONE";
alert( window['value'+1] );
But it is not good design. You should look into how to properly format JSON object.
I have something like this:
for(var i=0; i<2; i++)
{
var item = ARR[i];
for(var x=0;x<5;x++){
var hPropertyName = 'home_p' + (x+1);
var aPropertyName = 'away_p' + (x+1);
item[hPropertyName] = ARR[i][hPropertyName];
item[aPropertyName] = ARR[i][aPropertyName];
}
and it works when i create an array:
var ARR = [
{
home_p1: 4,
away_p1: 5,
home_p2: 8,
away_p2: 9,
home_p3: 2,
away_p3: 1,
home_p4: 5,
away_p4: 3,
home_p5: 3,
away_p5: 2
},
{
home_p1: 6,
away_p1: 1,
home_p2: 1,
away_p2: 2,
home_p3: 3,
away_p3: 4,
home_p4: 5,
away_p4: 6,
home_p5: 3,
away_p5: 2
}
];
but I don't have to create an array, because i have to work on object which I get from database :
[Object { event_id=19328, home_result=3, away_result=2, home_p1=4, away_p1=3, home_p2=1, away_p2=2 ...... }]
I'm only interested in these parameters --> home_p , away_p
I want to push it to my array to looks like ARR. I think i should convert an object which I get to an array
If you are using string name for your attributes then you could try using template literals?
var someObject = {}
for(let i=0 ; i<values.length ; i++){
someObject[`home${i+1}`] = values[i];
}
and if you need it to be ES5 you could just use string concatenation. Below is a working example:
values = [1,2,3,4,5];
let someObject = {};
for(let i=0 ; i<values.length ; i++){
someObject[`value${i+1}`]=values[i];
}
console.log(someObject.value1);
console.log(someObject.value2);
console.log(someObject.value3);
console.log(someObject.value4);
console.log(someObject.value5);

Javascript: Getting all existing keys in a JSON array

I have a JSON array like below:
var jsonArray = [{"k1":"v1"},{"k2":"v2"},{"k3":"v3"},{"k4":"v4"},{"k5":"v5"}]
I don't know which keys does exists in this array.
I want to get all the existing key from the array.
It should be possible something like this:
for(i=0;i<jsonArray.lenght;i++){
// something like- key = jsonArray[i].key
// alert(key);
}
Please tell me the method or way to get all keys existing in Json array.
Regards
Why don't you use a
var jsonObject = {"k1":"v1","k2":"v2","k3":"v3","k4":"v4","k5":"v5"}
instead of your
var jsonArray = [{"k1":"v1"},{"k2":"v2"},{"k3":"v3"},{"k4":"v4"},{"k5":"v5"}]
? Then the solution would be so simple: Object.keys(jsonObject).
Try this:
var L = jsonArray.length;
for (var i = 0; i < L; i++) {
var obj = jsonArray[i];
for (var j in obj) {
alert(j);
}
}
I've also made some modifications of your current code (like length caching).
Loop through the object properties, and select the first "real" one (which given your data schema should be the only real one).
var jsonArray = [{"k1":"v1"},{"k2":"v2"},{"k3":"v3"},{"k4":"v4"},{"k5":"v5"}]
for (var i = 0; i < jsonArray.length; i++) {
for (var prop in jsonArray[i]) {
if (jsonArray[i].hasOwnProperty(prop)) {
var key = prop;
break;
}
}
alert(key);
}
See How to loop through items in a js object? for an explanation of why it's important to use hasOwnProperty here.
Try this:
jsonArray.reduce(function(keys, element){
for (key in element) {
keys.push(key);
}
return keys;
},[]);
This should also work for multiple keys in the array objects.
If you're supporting old browsers that don't have reduce and map, then consider using a shim.
var id = { "object": "page", "entry": [{ "id": "1588811284674233", "time": 1511177084837, "messaging": [{ "sender": { "id": "1393377930761248" }, "recipient": { "id": "1588811284674233" }, "timestamp": 1511177084553, "message": { "mid": "mid.$cAAX_9pLcfu1mCnGmiVf2Sxd2erI2", "seq": 1882, "text": "a" } }] }] };
function getKey(obj, data) {
//#author dvdieukhtn#gmail.com
var data = data || [];
if (obj) {
var keys = Object.keys(obj);
for (var pos in keys) {
console.log();
data.push(keys[pos]);
if ((obj[keys[pos]].constructor === Array)) {
for (var i = 0; i < obj[keys[pos]].length; i++) {
getKey(obj[keys[pos]][i], data);
}
}
else if (obj[keys[pos]].constructor === Object) {
getKey(obj[keys[pos]], data);
}
}
return data;
}
}
console.log(getKey(id));

Getting count of object based on condition

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

loop a JS Object

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);

Categories

Resources