How to get the 'Value' using 'Key' from json in Javascript/Jquery - javascript

I have the following Json string. I want to get the 'Value' using 'Key', something like
giving 'BtchGotAdjust' returns 'Batch Got Adjusted';
var jsonstring=
[{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"},]

Wow... Looks kind of tough! Seems like you need to manipulate it a bit. Instead of functions, we can create a new object this way:
var jsonstring =
[{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"},];
var finalJSON = {};
for (var i in jsonstring)
finalJSON[jsonstring[i]["Key"]] = jsonstring[i]["Value"];
You can use it using:
finalJSON["BtchGotAdjust"]; // Batch Got Adjusted

As you have an array in your variable, you have to loop over the array and compare against the Key-Property of each element, something along the lines of this:
for (var i = 0; i < jsonstring.length; i++) {
if (jsonstring[i].Key === 'BtchGotAdjust') {
console.log(jsonstring[i].Value);
}
}
By the way, I think your variable name jsonstring is a little misleading. It does not contain a string. It contains an array. Still, the above code should give you a hint in the right direction.

Personally I would create a map from the array and then it acts like a dictionary giving you instantaneous access. You also only have to iterate through the array once to get all the data you need:
var objectArray = [{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"}]
var map = {}
for (var i=0; i < objectArray.length; i++){
map[objectArray[i].Key] = objectArray[i]
}
console.log(map);
alert(map["BtchGotAdjust"].Value)
alert(map["UnitToUnit"].Value)
See js fiddle here: http://jsfiddle.net/t2vrn1pq/1/

Related

Split json data using comma

I have a json which has a key "tag", which is returning data like this
"tags": "jname,gender,city"
but i want to append these value in separate span like below
<div class="info">
<span>jname</span><span>gender</span><span>city</span>
</div>
I am trying with this
$.getJSON("data.json", function(tagsposts) {
var items = [];
splitsVal = tag.split(",");
for (var i = 0; i < splitsVal.length; i++) {
obj.push({name:splitsVal[i]});
obj[i] = '<span>' + obj[i] + '</span>';
$('.tags-div').append(obj[i])
}
$.each(tagsposts, function(key, val) {
items.push('' + val['tags'] + '');
});
$('#tagsposts').append(items.join(""));
});
Am I doing correct
You're trying to split an undefined variable:
function(tagsposts) {
var items = [];
splitsVal = tag.split(","); // but tag doesn't exist...
(If you look at your browser console, which you should get into the habit of doing, you'll get a very clear message about why this isn't working: "ReferenceError: Can't find variable: tag".)
Since you haven't provided your JSON it's not possible to say exactly how to fix this. Assuming the full JSON is of the form
{"tag": "foo,bar,baz"}
then you would want
splitsVal = tagsposts.tag.split(",")
If there's more structure than that inside the JSON, you'll need to crawl down through that parsed object to find the "tag" value(s) you need.
There are lots of other problems here, however.
You also try to push onto an undefined array named obj; you'd need at least a var obj = [] outside that for loop. Though it's not clear why you're using obj at all, or trying to draw an object {name: val} into the DOM instead of just the value. What you're trying to do is just read splitsVal[i] so you can just do this:
for (var i = 0; i < splitsVal.length; i++) {
$('.tags-div').append('<span>'+splitsVal[i]+'</span>')
}
And you try to iterate over tagsposts as if it's an array when generating the #tagsposts contents. (Is your JSON an array? If so you need to iterate over it when getting the tag values too.)

Print data value of array

I have a array that has IDs in JavaScript:
["1649545","1649546","1649547"] etc.
And I want to print the values of this array in a URL, so something like this the foreach function of PHP does;
foreach
www.google.com/[valueofarray]
end
I know the solution could be very easy, but I just cannot manage to find it.
I made a fiddle and used a for loop this is without the use of jQuery but only javascript. I made an example array called myArray, I used .length so that javascript stops when he's been through all of the strings in the example array.
var myArray = ['12345', '123456', '1234567'];
for (var i = 0; i < myArray.length; i++) {
console.log('http://foo.com/' + myArray[i]);
// alert(myArray[i]);
}
See it work (and be sure to open your browsers console or use alert instead for viewing the output)
jsFiddle
var p='http:',a=["1649545","1649546","1649547"],u='www.google.com';for(i=0; i<a.length; ++i) console.log([p,'',u,a[i]].join('/'));
Try this:
var idArray = ["1649545","1649546","1649547"];
var url = "www.google.com/";
idArray.forEach(function(id){
console.log("http://" + url + id);
});
https://jsfiddle.net/tcmn2Lda/

accessing nested properties based on structure

Could anyone please give me an alternate syntax to the following
var id = '-JLxSeCPUCVN13FxifTY';
var ResultsContainer = results[id];
var i=0;
for(var k in ResultsContainer)
{
var TheArrayOfObjectsThatIneed = ResultsContainer[Object.keys(ResultsContainer)[i]];
console.log(TheArrayOfObjectsThatIneed);
//loop the TheArrayOfObjectsThatIneed do the processing
i++;
}
as you see in the image i have an array within an object within an object and i have no idea what the property names are but the structure is always the same {results:{id:{idthatidontknow:[{}]}}} and all i need is to access the arrays
the above code is working nicely but i am new to javescript and i was wondering if there is a nicer syntax and if i am doing it the right way
Perhaps something like this?
var id = '-JLxSeCPUCVN13FxifTY';
var ResultsContainer = results[id];
for(var k in ResultsContainer) {
if (ResultsContainer.hasOwnProperty(k)) {
var TheArrayOfObjectsThatIneed = ResultsContainer[k];
console.log(TheArrayOfObjectsThatIneed);
//loop the TheArrayOfObjectsThatIneed do the processing
}
}

access javascript array element by JSON object key

I have an array that looks like this
var Zips = [{Zip: 92880, Count:1}, {Zip:91710, Count:3}, {Zip:92672, Count:0}]
I would like to be able to access the Count property of a particular object via the Zip property so that I can increment the count when I get another zip that matches. I was hoping something like this but it's not quite right (This would be in a loop)
Zips[rows[i].Zipcode].Count
I know that's not right and am hoping that there is a solution without looping through the result set every time?
Thanks
I know that's not right and am hoping that there is a solution without
looping through the result set every time?
No, you're gonna have to loop and find the appropriate value which meets your criteria. Alternatively you could use the filter method:
var filteredZips = Zips.filter(function(element) {
return element.Zip == 92880;
});
if (filteredZips.length > 0) {
// we have found a corresponding element
var count = filteredZips[0].count;
}
If you had designed your object in a different manner:
var zips = {"92880": 1, "91710": 3, "92672": 0 };
then you could have directly accessed the Count:
var count = zips["92880"];
In the current form, you can not access an element by its ZIP-code without a loop.
You could transform your array to an object of this form:
var Zips = { 92880: 1, 91710: 3 }; // etc.
Then you can access it by
Zips[rows[i].Zipcode]
To transform from array to object you could use this
var ZipsObj = {};
for( var i=Zips.length; i--; ) {
ZipsObj[ Zips[i].Zip ] = Zips[i].Count;
}
Couple of mistakes in your code.
Your array is collection of objects
You can access objects with their property name and not property value i.e Zips[0]['Zip'] is correct, or by object notation Zips[0].Zip.
If you want to find the value you have to loop
If you want to keep the format of the array Zips and its elements
var Zips = [{Zip: 92880, Count:1}, {Zip:91710, Count:3}, {Zip:92672, Count:0}];
var MappedZips = {}; // first of all build hash by Zip
for (var i = 0; i < Zips.length; i++) {
MappedZips[Zips[i].Zip] = Zips[i];
}
MappedZips is {"92880": {Zip: 92880, Count:1}, "91710": {Zip:91710, Count:3}, "92672": {Zip:92672, Count:0}}
// then you can get Count by O(1)
alert(MappedZips[92880].Count);
// or can change data by O(1)
MappedZips[92880].Count++;
alert(MappedZips[92880].Count);
jsFiddle example
function getZip(zips, zipNumber) {
var answer = null;
zips.forEach(function(zip){
if (zip.Zip === zipNumber) answer = zip;
});
return answer;
}
This function returns the zip object with the Zip property equal to zipNumber, or null if none exists.
did you try this?
Zips[i].Zip.Count

arranging elements in to a hash array

I am trying to break a javascript object in to small array so that I can easily access the innerlevel data whenever I needed.
I have used recursive function to access all nodes inside json, using the program
http://jsfiddle.net/SvMUN/1/
What I am trying to do here is that I want to store these in to a separate array so that I cn access it like
newArray.Microsoft= MSFT, Microsoft;
newArray.Intel Corp=(INTC, Fortune 500);
newArray.Japan=Japan
newArray.Bernanke=Bernanke;
Depth of each array are different, so the ones with single level can use the same name like I ve shown in the example Bernanke. Is it possible to do it this way?
No, you reduce the Facets to a string named html - but you want an object.
function generateList(facets) {
var map = {};
(function recurse(arr) {
var join = [];
for (var i=0; i<arr.length; i++) {
var current = arr[i].term; // every object must have one!
current = current.replace(/ /g, "_");
join.push(current); // only on lowest level?
if (current in arr[i])
map[current] = recurse(arr[i][current]);
}
return join;
})(facets)
return map;
}
Demo on jsfiddle.net
To get the one-level-data, you could just add this else-statement after the if:
else
map[current] = [ current ]; // create Array manually
Altough I don't think the result (demo) makes much sense then.

Categories

Resources