Get KEY from JSON - javascript

Following JSON : https://api.myjson.com/bins/3yz34
I was thinking I might use an internal ID for a key (which simplifies looping through several entities and setting up data gathering) and use a value for display. However, I cannot get the value of the key.
$.each(tabledata.Companies, function (){
company = this;
alert(company);
var test = Object.keys( company );
console.log(test);
});
Object.keys() just gives me the number of characters in the value.
var test = Object.keys( company );
Returns:
["0", "1", "2", "3", "4", "5", "6", "7"]
["0", "1", "2", "3", "4", "5", "6", "7", "8"]
["0", "1", "2", "3", "4", "5", "6"]
["0", "1", "2", "3", "4"]
["0", "1", "2", "3", "4", "5", "6"]
Which seems to be the number of characters from the value in the key-value pair? Pretty stuck on this one, any ideas? Or maybe setup the JSON differently?
Thanks in advance!

Change the signature of your loop function to pass in the parameters
$.each(tabledata.Companies, function(key, value) {...}
See demo below
DEMO UPDATED based on comments
var tabledata = {
"Companies": {
"8df135f4-db42-486c-8d8c-fbbdd561c25e": "Phillips",
"47d946e3-56db-4bc7-8472-3809eb48506d": "Bauknecht",
"3ae13b97-7a09-4342-8953-c1d5a55687db": "Capitol",
"fb017214-dbc1-4b71-8080-4f9b530f4b49": "Bosch",
"50ede412-4eb0-429b-8d73-a1bfef41ebbc": "LG Corp"
},
"Pets": {
"dog": "Snoopy",
"cat": "Silvester",
"bird": "Sweetie",
"snake": "Snaker",
"fish": "Goldie Locks"
}
}
var attributeName="Companies";
$(function() {
$.each(tabledata[attributeName], function(key, value) {
console.log("KEY:" + key + " -> Value:" + value);
});
attributeName="Pets";
$.each(tabledata[attributeName], function(key, value) {
console.log("KEY:" + key + " -> Value:" + value);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Related

How to make a new array of strings derived from an old array, using a delimeter

I have an array of strings and I want to make a new one joining the strings of the arrays until the delimeter character is shown.For example I have this array of strings:
["5", "2", "0", "1", "6", "2", "7", "0", "1", "9", "9", "0", "0", "", "5", "2", "0", "3", "4", "1", "1", "0", "2", "1", "9", "8", "4", ""]
and I want to make a new one like this:
["5201627019900","5203411021984"]
The delimeter of those items in the array is the "" between them.Any help?
var result = array.join("").trim().split(/\s/ /*or " " */);
var result = array.reduce((a,b) => { return a+b; }).trim().split(" ");

How to count the items in array like the developer console

Script:
vL1 = ["AB", "AB", "AB", "AB", "AB", "CS", "CS", "CS", "ND", "ND"];
vL2 = ["1", "1", "1", "2", "3", "1", "1", "2", "1", "1"];
for(var i = 0; i < vL1.length; i++){
thing = vL1[i] + " " + vL2[i];
console.log(thing);
}
When I check the developer console, I see the following:
(3) AB 1
AB 2
AB 3
(2) CS 1
CS 2
(2) ND 1
How can I modify the script so I can get the number of times AB with 1 appeared or CS with 1 appeared in my code to be used in other functions?
I just want to know the count for each vL2 that is represented in vL1. It is important to associate vL1 because that will let me identify the vL2, since it is not unique.
You might also do as follows;
var vL1 = ["AB", "AB", "AB", "AB", "AB", "CS", "CS", "CS", "ND", "ND"],
vL2 = ["1", "1", "1", "2", "3", "1", "1", "2", "1", "1"],
result = vL1.reduce((p,c,i) => p[c] ? (p[c][vL2[i]] = p[c][vL2[i]] ? ++p[c][vL2[i]]
: 1, p)
: (p[c] = {[vL2[i]]: 1}, p), {});
console.log(result);
You can store the counts in an object. Also, utilizing Array.prototype.reduce can make it simpler to work with the indexes (e.g. you don't have to handle incrementing the index manually, etc.):
vL1 = ["AB", "AB", "AB", "AB", "AB", "CS", "CS", "CS", "ND", "ND"];
vL2 = ["1", "1", "1", "2", "3", "1", "1", "2", "1", "1"];
var counts = vL1.reduce(function(counts,vL1Element,index) {
//initialize this index if it isn't set
if(counts[vL1Element] == undefined) {
counts[vL1Element] = {};
}
//set this count to 0 if it hasn't been set yet
if (counts[vL1Element][vL2[index]] == undefined) {
counts[vL1Element][vL2[index]] = 0;
}
counts[vL1Element][vL2[index]]++;
return counts;
},{});
console.log(counts);
var obj={};
function log(a){
if(obj[a]){
obj[a]++;
}else{
obj[a]=0;
}
}
And then do:
log(thing);
Inside of your for loop, and than:
console.log(obj);
Obj now contains:
AB1:3;
....

How to iterate an array value to all the elements of another array

I have 2 arrays: cars & bikes.
I want to compare each element of car array to all the other elements of bike array, If both are equal, then alert true else false.
$scope.getComparison = function() {
$scope.bikes = ["1", "3", "3", "2", "6", "55", "45", "36", "18"];
angular.forEach($scope.bikes, function(value, key) {
$scope.p_Id = value.bikes;
$scope.cars = ["1", "2", "3", "4", "54", "55", "56", "56", "58"];
angular.forEach($scope.cars, function(value, key) {
$scope.b_Id = value.cars;
if ($scope.p_Id == $scope.b_Id) {
alert(b_Id + "=" + p_Id + "=" + "true");
} else {
alert(b_Id + "=" + p_Id + "=" + "false");
}
});
});
};
Where am I wrong ? I need help.
Not working!
var _firstArray = ["1", "3", "3", "2", "6", "55", "45", "36", "18"];
var _secondArray=["1", "2", "3", "4", "54", "55", "56", "56", "58"];
var areEqual = true;
_firstArray.forEach(function(item) {
if (!(item in _secondArray)) {
areEqual = false;
}
});
console.log(areEqual);
EDIT: I was wrong about the "in" operator. It only checks properties for a given object.
"45" in _firstArray will result in false, but 0 in _firstArray will result in true as 0 is a property for that array, 'length' in _firstArray will result in true as well. Here is a working solution:
var _firstArray = ["1", "3", "3", "2", "6", "55", "45", "36", "18"];
var _secondArray=["1", "2", "3", "4", "54", "55", "56", "56", "58"];
_firstArray.forEach(function(item1) {
_secondArray.forEach(function (item2) {
if (item1 === item2) {
console.log(item1 + '=' + item2 + '=' + 'true');
} else {
console.log(item1 + '=' + item2 + '=' + 'false');
}
});
});
try this :
$scope.bikes = ["1", "3", "3", "2", "6", "55", "45", "36", "18"];
$scope.cars = ["1", "2", "3", "4", "54", "55", "56", "56", "58"];
angular.forEach($scope.bikes, function(bike) {
angular.forEach($scope.cars, function(car) {
if (bike == car) {
alert(bike + "=" + car + "=" + "true");
} else {
alert(bike + "=" + car+ "=" + "false");
}
});
});
You can use forEach & indexOf array methods to find the match
var _firstArray = ["1", "3", "3", "2", "6", "55", "45", "36", "18"];
var _secondArray=["1", "2", "3", "4", "54", "55", "56", "56", "58"];
_firstArray.forEach(function(item){
if (_secondArray.indexOf(item) !==-1){
console.log(item)
}
else{
console.log("not matched");
}
})
Note: You can same array methods in your code
Check this jsfiddle
Hope this is what you're looking for
jsFiddle link - https://jsfiddle.net/U3pVM/25016/ . Replaced alert with console
$scope.getComparison = function() {
$scope.bikes = ["1", "3", "3", "2", "6", "55", "45", "36", "18"];
angular.forEach($scope.bikes, function(value, key) {
$scope.p_Id = value;
$scope.cars = ["1", "2", "3", "4", "54", "55", "56", "56", "58"];
angular.forEach($scope.cars, function(value, key) {
$scope.b_Id = value;
if ($scope.p_Id == $scope.b_Id) {
alert($scope.b_Id + "=" + $scope.p_Id + "=" + "true");
} else {
alert($scope.b_Id + "=" + $scope.p_Id + "=" + "false");
}
});
});
};
value argument of the forEach() method already represents the bike in the array as such, same goes for the car:
You can change your code like this:
$scope.getComparison = function() {
$scope.bikes = ["1", "3", "3", "2", "6", "55", "45", "36", "18"];
angular.forEach($scope.bikes, function(value, key) {
$scope.p_Id = value;
$scope.cars = ["1", "2", "3", "4", "54", "55", "56", "56", "58"];
angular.forEach($scope.cars, function(value, key) {
$scope.b_Id = value;
if ($scope.p_Id == $scope.b_Id) {
alert(b_Id + "=" + p_Id + "=" + "true");
} else {
alert(b_Id + "=" + p_Id + "=" + "false");
}
});
});
};
And it should work.
You can also nest the forEach() methods like such:
$scope.getComparison = function() {
$scope.bikes = ["1", "3", "3", "2", "6", "55", "45", "36", "18"];
$scope.cars = ["1", "2", "3", "4", "54", "55", "56", "56", "58"];
angular.forEach($scope.bikes, function(bikeValue, bikeKey) {
angular.forEach($scope.cars, function(carValue, carKey) {
if (bikeValue == carValue) {
alert(bikeValue + "=" + carValue + "=" + "true");
} else {
alert(bikeValue + "=" + carValue + "=" + "false");
}
});
});
};
This way directly compare them without saving the values to $scope.
Comparing each element of 1 array with each element of another array?
2 each's means use 2 loops thats it.
There were some issue with your code, try below code and should work perfectly:
$scope.getComparison = function() {
$scope.bikes = ["1", "3", "3", "2", "6", "55", "45", "36", "18"];
angular.forEach($scope.bikes, function(value, key) {
$scope.p_Id = value;
$scope.cars = ["1", "2", "3", "4", "54", "55", "56", "56", "58"];
angular.forEach($scope.cars, function(value, key) {
$scope.b_Id = value;
if ($scope.p_Id == $scope.b_Id) {
alert($scope.b_Id + "=" + $scope.p_Id + "=" + "true");
} else {
alert($scope.b_Id + "=" + $scope.p_Id + "=" + "false");
}
});
});
};

Access JSON data returned from CMS

The CMS I am using will give me JSON data of each item within a database. I use the following code to access this data:
var items = new BCAPI.Models.WebApp.ItemCollection("Strain Bank");
items.fetch({
success: function (items) {
items.each(function (item) {
item.fetch({
success: function (itemDetails) {
console.log(JSON.stringify(itemDetails.attributes))
}
});
});
}
});
This console.log(JSON.stringify(itemDetails.attributes)) outputs the following code for each item. An example of an items code is below:
{
"id": 4441485,
"name": "Alien OG",
"fields": {
"Buzz Length": "580",
"Strength": "37",
"Sativa Percentage": "231",
"Overall Rating": "40",
"Flower Time": "61",
"Potency": "10",
"Yield": "10",
"Height": "20",
"Reviews": "4",
"Grow Reviews": "1",
"Creative": "2",
"Euphoric": "0",
"Uplifted": "0",
"Energetic": "2",
"Lazy": "0",
"Focused": "2",
"Happy": "1",
"Talkative": "0",
"Giggly": "0",
"Tingly": "0",
"Hungry": "0",
"Sleepy": "0",
"Aroused": "0",
"Migraines": "1",
"Nausea": "0",
"Insomnia": "0",
"Pain": "2",
"Anxiety": "0",
"Stress": "2",
"PMS": "0",
"Lack of Appetite": "0",
"Muscle Spasms": "0",
"Depression": "2",
"Seizures": "0",
"Fatigue": "1",
"Fruity": "0",
"Citrus": "0",
"Seasonings-Spicy": "1",
"Floral": "2",
"Pungent": "2",
"Chemical": "1",
"Earthy": "2",
"Sweet": "0",
"Grass": "1",
"Skunky": "0"
}
}
What I need to do is access the data within each item. I am unsure how to do this. I tried:
//Thecode below replaces console.log(JSON.stringify(itemDetails.attributes)) in the above example.
var json = JSON.stringify(itemDetails.attributes)
$.each($.parseJSON(json), function(idx, obj) {
console.log(obj.name);
});
When I try the above code I see two things in the console.log:
TypeError: obj is null
and
undefined
How do I properly access the JSON data?
You should be able to access data in each item by . notation, like itemDetails.attributes.id, itemDetails.attributes.name and itemDetails.attributes.fields
Replace below:
console.log(JSON.stringify(itemDetails.attributes))
With below and try
console.log(itemDetails.attributes.name);
You are accessing the desired object wrongly. Try,
$.each(xObj.fields, function (key, val) {
console.log(key + " : " + val);
});
DEMO

Append text to a value in a json arrray

How can I append a text to only the first value of an array and send the array back to the server. This is the response i am getting from the server
[{
"12": [ "12", "1", "2", "3" ]
}, {
"13": [ "13", "1", "2", "3" ]
}, {
"14": [ "14", "1", "2", "3" ]
}, {
"15": [ "15", "1", "2", "3" ]
}]
I want my array to now be like this so that i can pass this array to my data table.
var object = [{
12: ["12 hrs", "1", "2", "3"]
}, {
13: ["13 hrs", "1", "2", "3"]
}, {
14: ["14 hrs", "1", "2", "3"]
}, {
15: ["15 hrs", "1", "2", "3"]
}]
How can I append hrs to the first value?
Here's one easy method...
// Parse the string response from the server into an object
var obj = JSON.parse(serverResponse);
// loop through the object, knowing that it's nested in the first index of an array "obj[0]"
for(id in obj[0]){
// obj->arrayIndex->objectProperty->arrayIndex append " hrs"
obj[0][id][0] += " hrs";
}
// to return this to the server, apply JSON.stringify(obj)
I fixed object in your question to -
var objectArray = [{"12" : ["12", "1", "2", "3"]}, {"13" : ["13", "1", "2", "3"]},{"14" : ["14", "1", "2", "3"]},{"15" : ["15", "1", "2", "3"]}]
This is how you can loop through the objectArray and change in the way you wanted -
for(var i=0;i<objectArray.length;i++)
{
for(var key in objectArray[i])
{
objectArray[i][key][0]+=" hrs";
break;
}
}
console.log(objectArray)

Categories

Resources