How to fetch Dynamic keys from JavaScript Associative array? - javascript

I have a JSON string which I then convert into JSON Object by using jQuery. The string in question given below:
var json = [
{
"1240": [
"Order1",
"user1"
]
}
]
Here key 1240 is Dynamic and I can't do something like json[0]["1240"] When I do something like:
for(var f in json )
{
alert(f);
}
Then it returns "0"
How do I fetch 1240 here?

Because it's an array of objects.
http://jsbin.com/umaWoge/1/
Try this
var json = [
{
"1240": [
"Order1",
"user1"
]
}
];
for (var i = 0; i < json.length; i++)
{
for(var f in json[i])
{
alert(f);
}
}

try this also.
var json = [
{
"1240": [
"Order1",
"user1"
]
}
];
for (var i in json)
{
for(var f in json[i])
{
alert(f);
}
}

Related

Change the format of search result from JSON file

I am using javascript to search content from JSON file, below is my code:
var result = [];
var searchField = "equip_id";
for (var i=0 ; i < jsondata.array.length ; i++)
{
if (jsondata.array[i][searchField] == SelectedEquip) {
result.push(jsondata.array[i].group_name);
}
}
And the output is a group name with the following format:
["groupname"]
I only want the groupname without [] and "". Because I need to use the groupname to search another JSON file.
Anyone can help solve this problem?
If you want the result as a string, how about:
// Sample Data
var jsondata = {
array: [{
equip_id: 1,
group_name: "a"
}, {
equip_id: 2,
group_name: "b"
}, {
equip_id: 3,
group_name: "c"
}]
}, SelectedEquip = 3;
// Actual code
var result = '';
var searchField = "equip_id";
for (var i = 0; i < jsondata.array.length; i++) {
if (jsondata.array[i][searchField] == SelectedEquip) {
result = jsondata.array[i].group_name;
}
}
// Sample output
console.log(result);
Using your code above, result[0] will give you the same output. There's just no need to create and push to an array, if you are dealing with a single value.

Make denormalized JSON hierarchical

I'm working with denormalized JSON structures but I need nested JSON to iterate over them in multiple levels on the client side. I'm stumped how to do this elegantly.
Can you think how to easily transform JSON of the form
[{ category: xyz, attribute: 1},{ category: xyz, attribute: 2}]
into a hierarchical format:
[{category: xyz, attributes: [1,2]}] ?
Much much thanks for any solutions.
I do this all the time, though usually on the server side. The code looks something like this:
function normalize(key, outputKey, data)
{
var results = [];
var record;
for(var i=0; i<data.length; i++)
{
if(!record || record[key] != data[i][key])
{
record = {};
record[outputKey] = [];
record[key] = data[i][key];
results.push(record);
}
delete data[i][key];
record[outputKey].push(data[i]);
}
return results;
}
Here's the output:
[
{
"category": "xyz",
"values": [
{ "attribute": 1 },
{ "attribute": 2 }
]
}
]
Note that your example output is messed up. You might want to decide if you're trying to group objects or values of an array. The latter is even easier.
EDIT: Of course, you were looking for the boring answer. Here you go:
function collapse(key, attr, data)
{
var results = [];
var record;
for(var i=0; i<data.length; i++)
{
if(!record || record[key] != data[i][key])
{
record = data[i];
record[attr] = [data[i][attr]];
results.push(record);
}
else
{
record[attr].push(data[i][attr]);
}
}
return results;
}
If you call it like this:
var data = [{ category: 'xyz', attribute: 1},{ category: 'xyz', attribute: 2}];
collapse('category', 'attribute', data);
You'll get this output:
[{"category":"xyz","attribute":[1,2]}]
function reorder(arr) {
var heir = {};
arr.forEach(function(i){
for (var j in i) {
if (heir[j]) {
if (heir[j].indexOf(i[j]) == -1) {
heir[j].push(i[j]);
}
} else {
heir[j] = [i[j]];
}
}
});
for (var i in heir) {
if (heir[i].length == 1) {
heir[i] = heir[i][0];
}
}
return heir;
}
This won't perfectly conform to your example, but pretty close:
{ category: 'xyz', attribute: [ 1, 2 ] }
When I have to do stuff like this I usually build external arrays with metadata to improve code readability. So don't do it like this if your JSON is huge.
function normalize(json) {
var categories= [];
var norm= [];
for (var i=0; i < json.length; i++) {
if (categories.indexOf(json[i].category) !== -1) {
categories.push(json[i].category);
}
}
for (var i=0; i < categories.length; i++) {
norm.push({ category: categories[i]; attributes: []});
}
for (var i=0; i < json.length; i++) {
norm[categories.indexOf(json[i].category)].attributes.push(json[i].attribute);
}
return norm;
}
My answer is O(n*log(m) + n + n*m), where n is the length of the outermost json and m is the number of categories, but the n*log(m) and n*m are the indexOf part and it is done in native code by the browser. I'm too lazy to do proper big O comparison with the other answers, but this is clearly slower.

Iterating in a JSON in javascript

I have a JSON which looks like below.
[
{"Device":"Device1","Links"["NewLink","NewLink2","NewLink3"],"GeographicLocation":"NewLocation"},
{"Device":"Device2","Links":["NewLink"],"GeographicLocation":"NewLocation"}
{"Device":"Device3","Links":["NewLink","NewLink2"],"GeographicLocation":"NewLocation"}
]
I want to iterate through it and in the loop i want to alert the values of Links field.
How can I achieve this.
If you have a json as a string you can use
var json = JSON.parse(jsonString);
this will return an object array on which you can iterate.
See more here
var arr = [
{"Device":"Device1","Links" ["NewLink","NewLink2","NewLink3"],"GeographicLocation":"NewLocation"},
{"Device":"Device2","Links":["NewLink"],"GeographicLocation":"NewLocation"}
{"Device":"Device3","Links":["NewLink","NewLink2"],"GeographicLocation":"NewLocation"}
];
for(var i=0;i<arr.length;i++){
var obj = arr[i];
for(var key in obj){
var attrName = key;
var attrValue = obj[key];
}
}
Say you have your string json:
var data = JSON.parse(json);
for(var i=0; i<data.length; i++) {
var links = data[i]['Links'];
for(var j=0; j<links.length; j++) {
//append this wherever
document.write(links[j]);
//if you're using jQuery, $('body').append(links[j]);
}
}
[
{"Device":"Device1","Links":["NewLink","NewLink2","NewLink3"],"GeographicLocation":"NewLocation"},
{"Device":"Device2","Links":["NewLink"],"GeographicLocation":"NewLocation"},
{"Device":"Device3","Links":["NewLink","NewLink2"],"GeographicLocation":"NewLocation"}
]
var json = JSON.parse(jsonString);
now it will work
you have missed ":" and " , " in your JSON string
near the first "Links": and }, add this
var json = [
{
"Device": "Device1",
"Links": [
"NewLink",
"NewLink2",
"NewLink3"
],
"GeographicLocation": "NewLocation"
},
{
"Device": "Device2",
"Links": [
"NewLink"
],
"GeographicLocation": "NewLocation"
},
{
"Device": "Device3",
"Links": [
"NewLink",
"NewLink2"
],
"GeographicLocation": "NewLocation"
}
];
for(var i=0; i<json.length ; i++)
{
console.log(json[i].Device);
console.log(json[i].Links);
// for links use another loop
for(var j=0; j<json[i].Links.length ; j++)
{
console.log(json[i].Links[j]);
}
console.log(json[i].GeographicLocation);
}

JavaScript looping through an array to check for numeric values

I have an an array that returns the values such as the following:
//Eg 1 [ [ "214323", "34243" ], [ "3333", "123" ] ]
//Eg 2 [ [ "214323" ],[ "3333" ] ]
I want to validate if the array holds only numbers with no spaces or null, else I would like to throw an error.
This is my following code and it does not work in the above example. It throws out an error even though all values are numeric.
for (var i = 0; i <= arrayVals.length; i++) {
if(!(/^\d+$/.test(arrayVals[i]))) {
err_comp=true;
}
}
if( err_comp ==true) {
alert( 'The value has to be only numeric.');
}
You have an array of arrays, thus you need two loops:
var err_comp = false;
for (var i = 0; i < arrayVals.length; i++) {
var arr = arrayVals[i];
for (var j = 0; j < arr.length; j++) {
if (!(/^\d+$/.test(arr[j]))) {
err_comp = true;
}
}
}
Otherwise, you'd be testing /^\d+$/.test([ "214323", "34243" ]).
you should not use <= because you start with 0 you should use <:
for (var i = 0; i < arrayVals.length;
multi_arr.every(function(arr) {
return arr.every(function(n) {
return /^\d+$/.test(n);
});
});
You can change the test as you need, and you can add a .every patch for IE8 if you want.
And you can make reusable your functions.
function forEveryArray(fn) {
return function every_array(arr) {
return arr.every(fn)
}
}
function isNumber(n) { return /^\d+$/.test(n); }
multi_arr.every(forEveryArray(isNumber));

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

Categories

Resources