How to find value in json [duplicate] - javascript

This question already has answers here:
JavaScript find json value [duplicate]
(5 answers)
Closed 7 years ago.
How to fine state name using postcode in bellow json data;
var data = '{
"1": {
"state": "VIC",
"postcode": "2600,2603,2605,2606"
},
"2": {
"state": "NSW",
"postcode": "2259,2264"
}
}'
How to find state by postcode;
if i search postcode 2600 if get result like VIC

Remove '' as yours is not a valid string, remove '' to make it a valid object literal, then you can iterate over the keys of the Object and check if it has the matching POSTCODE and if it has then return it's corresponding state.
var data = {
"1": {
"state": "VIC",
"postcode": "2600,2603,2605,2606"
},
"2": {
"state": "NSW",
"postcode": "2259,2264"
}
};
function getState(data, postcode){
for(var x in data){
if(data[x].postcode && data[x].postcode.split(",").indexOf(postcode.toString())!=-1) return data[x].state;
}
return "Not Found";
}
alert(getState(data, "2600"));
alert(getState(data, 2264));
You can directly do .indexOf on the postcode, even without using .split(","). But, then, it will also match with ,2600 which should not be the case. So, use split.
Use json[x].postcode condition to make sure that postcode field exists in the object. Otherwise, it will give an error if it does not exist.

Try like this
var data = '{"1": { "state": "VIC","postcode": "2600,2603,2605,2606"}, "2": {"state": "NSW","postcode": "2259,2264"}}';
var jsObj = JSON.parse(data);
var find = "2600";
var values = Object.keys(jsObj).filter(function(x) {
return jsObj[x].postcode.indexOf(find) > -1;
}).map(function(x) {
return jsObj[x].state;
});
console.log(values.length > 0 ? values[0] : "not found");
JSFIDDLE

function findState(data, postcode) {
var postcode = postcode.toString()
for (var k in data) {
var postcodes = data[k].postcode.split(",")
if (postcodes.indexOf(postcode) != -1)
return data[k].state
}
}
// Demo Output
var data = '{"1":{"state":"VIC","postcode":"2600,2603,2605,2606"},"2":{"state":"NSW","postcode":"2259,2264"}}'
var dataObj = JSON.parse(data)
var state = findState(dataObj, 2600)
document.write(state)

You can try something like this:
function searchInObject(object, searchKey, searchValue) {
for (var i in object) {
if (object[i][searchKey].indexOf(searchValue) > -1) {
return object[i];
}
}
}
(function() {
var data = {
"1": {
"state": "VIC",
"postcode": "2600,2603,2605,2606"
},
"2": {
"state": "NSW",
"postcode": "2259,2264"
}
}
var pin = "2600";
var result = searchInObject(data, "postcode", pin);
console.log(result.state);
pin = "2259";
result = searchInObject(data, "postcode", pin);
console.log(result.state);
})()

Well now.. You are just asking us to help you with homework :) Good thing im in a good mood.
First get a proper JSON string, and parse it into a object using JSON.parse. Then iterate this object and split the postcode string and find the state!
var data = ......
var resp = JSON.parse(data);
function getStateByPostcode(postcode) {
var state = "";
for(var i in resp) {
if(resp.hasOwnProperty(i)) {
var postcodes = resp[i]['postcode'].split(',');
if(postcodes.indexOf(postcode) !== -1) {
return resp[i]['state'];
}
}
}
return state;
}

Related

javascript object filter using user_id not return expect result

I have below object
var total_hours = <?php echo json_encode($total_hours); ?>;
[
{"user_id": 2959
"total_hours": "38"
}
{"user_id": 116
"total_hours": "1"
}
]
i want to get total_hours base on user_id
var user = document.getElementById("user").value;
var yahooOnly = total_hours.filter(function (entry) {
return entry.user_id === user;
});
total_hours = yahooOnly;
but um unable to get required output. Can someone helps me?
Try this question but didn't get required output!
filter() returns an array. You need to index it and then access the total_hours property.
You can use .find() instead of .filter() to get the object instead of an array.
var total_hours = [{
"user_id": 2959,
"total_hours": "38"
}, {
"user_id": 116,
"total_hours": "1"
}];
var user = 2959;
var yahooOnly = total_hours.find(entry => entry.user_id == user);
var yahoo_hours = yahooOnly.total_hours;
console.log(yahoo_hours)

How to print JSON file Using Java Script

var user_business_data =[
{
"user_id":"5db3e3b1",
"blog":{
"blog_id":"128c522e"
},
"business_units":[
{
"business_unit_id":"000396c9",
"viewing":101
},
{
"business_unit_id":"01821e44",
"viewing":102
},
{
"business_unit_id":"02cbcad5",
"viewing":103
}
]
}
]
I want to get all the "business_unit_id" and store in a varible. for this i need get all the "business_unit_id". so i tried to print all the id's with the below code but i was unable to print.
if (undefined !== user_business_data.business_units && user_business_data.business_units.length) {
for(var i=0;i<user_business_data.business_units.length;i++){
var key = user_business_data.business_units[i];
console.log("Key : "+key, "Values : "+user_business_data.business_units[key]);
}
} else {
console.log("Undefined value");
}
There always i am getting undefined value.
var user_business_data=[{"user_id":"5db3e3b1","blog":{"blog_id":"128c522e"},"business_units":[{"business_unit_id":"000396c9","viewing":101},{"business_unit_id":"01821e44","viewing":102},{"business_unit_id":"02cbcad5","viewing":103}]}]
var unit_ids = [];
user_business_data.forEach(function(user) {
user.business_units.forEach(function(business) {
unit_ids.push(business.business_unit_id);
});
});
console.log(unit_ids);
user_business_data is an array, not an object, so you either need to loop through it or read a specific index from it.
Also, key in your code will be an object (a single business unit object), so you can't print it directly - instead you need to fetch a specific property within the object.
Here's a simple demo reading the first key from the outer array and then listing all the specific properties from the business units. The code can be simplified further potentially, but this illustrates the point:
var user_business_data =
[{
"user_id": "5db3e3b1",
"blog": {
"blog_id": "128c522e"
},
"business_units": [{
"business_unit_id": "000396c9",
"viewing": 101
},
{
"business_unit_id": "01821e44",
"viewing": 102
},
{
"business_unit_id": "02cbcad5",
"viewing": 103
}
]
}]
if (undefined !== user_business_data[0].business_units && user_business_data[0].business_units.length) {
for (var i = 0; i < user_business_data[0].business_units.length; i++) {
var key = user_business_data[0].business_units[i].business_unit_id;
console.log("Key : " + key, "Values : " + user_business_data[0].business_units[i].viewing);
}
} else {
console.log("Undefined value");
}
I suggest you get clear in your head the difference between arrays, objects and properties in JSON / JS objects, and then this kind of thing will become trivial.
user_business_data is an array and not an object.If you want to access any object from an array you have to specify the index as of which position you are referring.Therefore in your example change it to following to work:
if (undefined !== user_business_data[0].business_units && user_business_data[0].business_units.length) {
for(var i=0;i<user_business_data[0].business_units.length;i++){
var key = user_business_data[0].business_units[i]. business_unit_id;
console.log("Key : "+key, "Values : "+user_business_data[0].business_units[key]);
}
} else {
console.log("Undefined value");
}
It's because user_business_data is an array, not an object yet you access it like user_business_data.business_units instead of user_business_data[0].business_units
var user_business_data = [{"user_id": "5db3e3b1","blog": {"blog_id": "128c522e"}, "business_units": [{"business_unit_id": "000396c9","viewing": 101}, {"business_unit_id": "01821e44","viewing": 102},{"business_unit_id": "02cbcad5","viewing": 103}]}];
// Both methods give the same result, but the second checks for null values.
var ids1 = user_business_data[0].business_units.map(x => x.business_unit_id)
console.log('Method 1:', ids1);
// The && check for null values, kinda like an if statement.
var data = user_business_data.length && user_business_data[0]
var units = data && data.business_units
var ids2 = units && units.length && units.map(x => x.business_unit_id)
console.log('Method 2:', ids2)
If you want to print only the business_unit_ids then you can do as follows:
var user_business_data =
[
{
"user_id": "5db3e3b1",
"blog": {
"blog_id": "128c522e"
},
"business_units": [
{
"business_unit_id": "000396c9",
"viewing": 101
},
{
"business_unit_id": "01821e44",
"viewing": 102
},
{
"business_unit_id": "02cbcad5",
"viewing": 103
}
]
}
]
for(var i=0;i<user_business_data[0]["business_units"].length;i++){
console.log(user_business_data[0]["business_units"][i].business_unit_id)
}

How to save distinct values in an object in javascript?

I have a bunch of log data which is stored in a variable. Each log value contains a camera name and system ip. I want to create an object which has names as all the distinct system ip's and corresponding value as an array which contains all the camera names corresponding to that system ip. Below is my code ---
$http(req).success(function(data){
$scope.logs = data;
$scope.cameras={};
var v =$scope.logs[0].systemIp;
$scope.cameras["v"]=[];
$scope.cameras["v"].push($scope.logs[0].cameraName);
for(i=1;i<$scope.logs.length;i++){
v=$scope.logs[i].systemIp;
var flag=0;
for(j in $scope.cameras){
if(j==="v")
{
flag=1;
break;
}
}
if(flag==0)
{
$scope.cameras["j"]=[];
$scope.cameras["j"].push($scope.logs[i].cameraName);
}
else if(flag==1)
{
$scope.cameras["v"].push($scope.logs[i].cameraName);
}
}});
And this is what my data looks like --
[{
"_id": "57683fd82c77bb5a1a49a2aa",
"cameraIp": "192.16.0.9",
"cameraName": "garage2",
"systemIp": "192.168.0.2"
},
{
"_id": "57683f8e2c77bb5a1a49a2a9",
"cameraIp": "192.16.0.8",
"cameraName": "garage1",
"systemIp": "192.168.0.2"
},
{
"_id": "57683f5e2c77bb5a1a49a2a8",
"cameraIp": "192.16.0.7",
"cameraName": "Back Door",
"systemIp": "192.168.0.4"
}]
When I print $scope.cameras on my console it gives this as the output -
Object { v: Array[3] }
I want by cameras object to look like this --
{ "192.168.0.2" : [ "garage1" , "garage2"] ,
"192.168.0.4" : [ "Back Door"] }
I am new to javascript, any help is appreciated.
If you are using the Lodash or Underscore library (which I highly recommend), you can just use the _.groupBy() function to do what you are after (along with some other functions to ensure all values are unique).
However, you can also easily implement it yourself:
function groupByDistinct(arr, prop, mapFn) {
mapFn = mapFn || function (x) { return x; };
var output = {};
arr.forEach(function (item) {
var key = item[prop],
val = mapFn(item);
if (!output[key]) {
output[key] = [val];
return;
}
if (output[key].indexOf(val) < 0) {
output[key].push(val);
}
});
return output;
}
Use it for your code like so:
$scope.cameras = groupByDistinct(data, 'cameraIp', function (logEntry) {
return logEntry.cameraName;
});
You are passing a string such as "v" or "j" as your object key, and this string are actually ending being your object key and not the value of this variables as you want. You can use something like this:
for(i=0; i < $scope.logs.length; i++){
var _sysIp = $scope.logs[i].systemIp,
_camName = $scope.logs[i].cameraName;
if(!$scope.cameras.hasOwnProperty(_sysIp)) {
$scope.cameras[_sysIp] = [_camName];
} else if ($scope.cameras[_sysIp].indexOf(_camName) < 0) {
$scope.cameras[_sysIp].push(_camName);
}
}

Find last JSON entry with value starting with

I need to find the key of last property starting with a string
JSON:
var data = {
"admin": "peterson",
"worker": "peter napier",
"housekeeper": "peterson",
"worker": "richard Ben",
"executive": "richard parker",
"executive": "peter alp",
"housekeeper": "richard johny",
"admin": "richardson"
};
I have to write an algorithm which will return the key corresponding to the last occurence of value starting with a string.
Ex: I need to get admin if I call findKey("richard")
I need to get executive if I call findKey("peter")
I have iterated the object using simple for loop as this
for (var key in yourobject) {
console.log(key, yourobject[key]);
}
But I like to know the fastest way of iterating this as my scenario has more than 100000 property.
Just iterate over your data and store each name beginning with your key :
function findkey(name) {
var lg = name.length,
found;
for(var line in data) {
if(data[line].length >= lg && data[line].substring(0,lg) === name) {
found = line;
}
}
return found;
}
Here you go
var findKey = function (string) {
var keyToReturn;
for(key in data){
if(data[key].indexOf(string) === 0)
keyToReturn = key;
}
return keyToReturn;
}

jQuery object get value by key

How would you get the value of assocIMG by key matching the key eg
if I have a var 11786 I want it to return media/catalog/product/8795139_633.jpg
var spConfig = {
"attributes": {
"125": {
"id": "125",
"code": "pos_colours",
"label": "Colour",
"options": [{
"id": "236",
"label": "Dazzling Blue",
"price": "0",
"oldPrice": "0",
"products": ["11148"]
}, {
"id": "305",
"label": "Vintage Brown",
"price": "0",
"oldPrice": "0",
"products": ["11786", "11787", "11788", "11789", "11790", "11791", "11792", "11793"]
}]
}
}
};
var assocIMG = // Added - Removed { here, causes issues with other scripts when not working with a configurable product.
{
11786: 'media/catalog/product/8795139_633.jpg',
11787: 'media/catalog/product/8795139_633.jpg',
}
Above is the objects I am working with and below is my current jQuery. Help would be greatly appreciated.
$('#attribute125').change(function() {
var image = $(this).val();
$.each(spConfig.attributes, function() {
prods = $(this.options).filter( function() { return this.id == image; } )[0].products[0];
alert(prods);
});
});
You can use bracket notation to get object members by their keys. You have the variable prods containing a string ("11786"), and the object assocIMG with various keys. Then just use
assocIMG[prods]
to get the property value 'media/catalog/product/8795139_633.jpg' which is associated with that key.
Note that you should always use strings as keys in your object literal, IE does not support numbers there:
var assocIMG = {
"11786": 'media/catalog/product/8795139_633.jpg',
"11787": 'media/catalog/product/8795139_633.jpg'
};
Another improvement to your script would be not to loop through the spConfig.attributes each time, and potentially execute your action multiple times if an image is contained in more than one attribute. Instead, build a hash object out of it, where you can just look up the respective product id.
var productById = {};
$.each(spConfig.attributes, function() {
$.each(this.options, function() {
var id = this.id;
productsById[i] = this.products[0];
});
});
$('#attribute').change(function() {
var id = this.value;
var prod = productById[id];
var image = assocIMG[prod];
$("#product_img").attr("src", image);
});
You should not use numbers as object keys (in their start). If you want to get the value associated with the 11786 integer key, you will need to use this syntax:
assocIMG["11786"] or assocIMG[11786]
Not
assocIMG.11786
The first thing that you need to do is to create your keys as strings, since you would have:
var assocIMG = {
"11786": 'media/catalog/product/8795139_633.jpg',
"11787": 'media/catalog/product/8795139_633.jpg',
}
But even doing this, you won't be able to access the field using assocIMG.11786 and the first valid sintax that I presented will still work. The correct approach would be:
var assocIMG = {
id11786: 'media/catalog/product/8795139_633.jpg',
id11787: 'media/catalog/product/8795139_633.jpg',
}
Or
var assocIMG = {
"id11786": 'media/catalog/product/8795139_633.jpg',
"id11787": 'media/catalog/product/8795139_633.jpg',
}
Note that the keys are now starting with letters, not numbers. And now, you will can access the 11786 field as assocIMG.id11786 or assocIMG["id11786"], not assocIMG[id11786]
To Get the Value from object by matching key I ended up with the following
$.each(assocIMG, function(index, value) {
if(index == prods) {
var image_path = value;
$("#product_img").attr("src", image_path);
//alert(image_path);
}

Categories