Creating an array in JavaScript from JSON file - javascript

My JSON file:
[{"val0":"Paul","val1":"Jake","val2":null,"val3":"Max"},
{"val0":"Sam","val1":"Tina","val2":"Emily","val3":"Hardwell"},
{"val0":"Tom","val1":"Julie","val2":null,"val3":"Adi"}]
I want to create an array in javascript as follows:
var dataSet=[
['Paul','Jake','null','Max'],
['Sam','Tina','Emily','Harwell'],
['Tom','Julie','null','Adi']
];
I tried the following code but it isn’t working. Can anybody please help?
$.getJSON("filename.json", function(data) {
var items = [];
$.each(data, function(key, val) {
items.push(val);
});
// …
});
I’m using this array for display purpose (using DataTables), so, I want to create the array in that format.I'm using the dataSet array for displaying in DataTables as follows:
var dataSet = [
['Paul','Jake','Isha','Mike','null','null','Parth','Tinker'],
['Tina','Michael','null','Blue','Red','','Emily','Mina']
];
$(document).ready(function() {
$('#demo').html( '<table cellpadding="0" cellspacing="0" border="0" class="display" id="example"></table>' );
$('#example').dataTable( {
"data": dataSet,
"columns": [
{ "title": "Name" },
{ "title": "Deadline" },
{ "title": "Additional fees" },
{ "title": "Requirements" },
{ "title": "Field" },
{ "title": "Award" },
{ "title": "Renewable requirements"},
{ "title": "Link" }
]
} );
} );

You get an array of objects, and you want an array of arrays, so convert each object to an array by reading the properties of the object:
var items = [];
$.each( data, function( key, val ) {
items.push([val.val0,val.val1,val.val2,val.val3]);
});

Try this
<script>
$(function() {
$.getJSON("filename.json", function(data) {
var items = [];
$.each(data, function(key, val) {
var tmp = [];
for (var Key in val) {
tmp.push(val[Key]);
}
items.push(tmp);
});
console.log(items);
});
});

A solution without jquery:
var data = [
{ "val0": "Paul", "val1": "Jake", "val2": null, "val3": "Max" },
{ "val0": "Sam", "val1": "Tina", "val2": "Emily", "val3": "Hardwell" },
{ "val0": "Tom", "val1": "Julie", "val2": null, "val3": "Adi" }
],
dataSet = data.reduce(function (r, a) {
var i, a0 = [];
for (i in a) {
a0.push(a[i]);
}
r.push(a0);
return r;
}, []);
document.getElementById('out').innerHTML = JSON.stringify(dataSet, null, 4);
<pre id="out"></pre>

One liner:
var dataSet = rawData.map(function(e){ return Object.keys(e).map(function(i){ return e[i]}); })
Output:
Output as JSON:
Method explanation (from Javascript Reference)
The map() method creates a new array with the results of calling a provided function on every element in this array.
The Object.keys() method returns an array of a given object's own enumerable properties

Related

group by/formatting json data in Javascript

Sorry if this has been asked before. I have the JSON structure like:
{"data":[
{"Date":"03/04/2016","Key":"A","Values":"123"},
{"Date":"04/04/2016","Key":"A","Values":"456"},
{"Date":"03/04/2016","Key":"B","Values":"789"},
{"Date":"04/04/2016","Key":"B","Values":"012"}
]}
I want to change this to a different format which is basically grouped by Key and combines rest of the field in Values
{"Result":[
{
"Key":"A"
"Values":[["03/04/2016","123"], ["04/04/2016","456"]]
},
{"Key":"B"
"Values":[["03/04/2016","789"]},["04/04/2016","012"]]
}
]}
I want to do this javascript/html
You could iterate and build a new object if not exist.
var object = { "data": [{ "Date": "03/04/2016", "Key": "A", "Values": "123" }, { "Date": "04/04/2016", "Key": "A", "Values": "456" }, { "Date": "03/04/2016", "Key": "B", "Values": "789" }, { "Date": "04/04/2016", "Key": "B", "Values": "012" }], result: [] };
object.data.forEach(function (a) {
if (!this[a.Key]) {
this[a.Key] = { Key: a.Key, Values: [] };
object.result.push(this[a.Key]);
}
this[a.Key].Values.push([a.Date, a.Values]);
}, Object.create(null));
console.log(object);
I think this can be a better answer (but Nina's answer is the match for your problem terms) if items of data array have different properties and you don't want to change input data.
var raw = {"data":[
{"Date":"03/04/2016","Key":"A","Values":"123"},
{"Date":"04/04/2016","Key":"A","Values":"456"},
{"Date":"03/04/2016","Key":"B","Values":"789"},
{"Date":"04/04/2016","Key":"B","Values":"012"}
]};
var result = new Map;
raw.data.forEach(entry => {
var key = entry.Key;
if (this[key])
return this[key].push(getClonedData(entry));
this[key] = [getClonedData(entry)];
result.set(key, {
Key: key,
Values: this[key]
})
}, Object.create(null));
var filtered = {
result: [...result.values()]
}
console.log(filtered);
function getClonedData(entry) {
data = Object.assign({}, entry);
delete data.Key;
return data;
}

Covert object to array of combinations/objects

Using lodash or underscore. I'm trying to convert this object:
{
"variations": {
"versions": ["sport", "generic"],
"devices": ["mobile", "tablet"]
}
}
to this:
var variations = [{
"version": "sport",
"device": "mobile"
}, {
"version": "sport",
"device": "tablet"
}, {
"version": "generic",
"device": "mobile"
}, {
"version": "generic",
"device": "tablet"
}];
What's the best/shortest method to do this?
Not sure with lodash or undesrcore. But with simple jquery i have done this. take a look.
var object={
"variations": {
"versions": ["sport", "generic"],
"devices": ["mobile", "tablet"]
}
};
var variations=[];
$.each(object.variations.versions, function(i, j) {
$.each(object.variations.devices, function(k, l) {
variations.push({version:j,device:l});
});
});
I think you wanna set object key to new variable name and do combinations of inside object values.
<script type="text/javascript">
//here I created two object keys for more clear
var json ={
"variations": {
"versions": ["sport", "generic"],
"devices": ["mobile", "tablet"]
},
"another_variations": {
"versions": ["sport", "generic"],
"devices": ["mobile", "tablet"]
}
};
for(var i in json){
window[i] = []; //here window[variable] will make global variable
ver = Object.keys(json[i])[0];//Object.keys(json[i]) get object keys ~["versions","devices"]
dev = Object.keys(json[i])[1];
window[i].push(
{
[ver]:json[i].versions[0],
[dev]:json[i].devices[0]
},
{
[ver]:json[i].versions[0],
[dev]:json[i].devices[1]
},
{
[ver]:json[i].versions[1],
[dev]:json[i].devices[0]
},
{
[ver]:json[i].versions[1],
[dev]:json[i].devices[1]
});
}
console.log(variations); //here can call object key as a variable name if you
console.log(another_variations);//don't use `window[variable]` in above, this will print undefined error
</script>
Found a solution using: https://gist.github.com/wassname/a882ac3981c8e18d2556
_.mixin({
cartesianProductOf: function(args) {
if (arguments.length > 1) args = _.toArray(arguments);
// strings to arrays of letters
args = _.map(args, opt => typeof opt === 'string' ? _.toArray(opt) : opt)
return _.reduce(args, function(a, b) {
return _.flatten(_.map(a, function(x) {
return _.map(b, function(y) {
return _.concat(x, [y]);
});
}), true);
}, [
[]
]);
},
cartesianProductObj: function(optObj) {
var keys = _.keys(optObj);
var opts = _.values(optObj);
var combs = _.cartesianProductOf(opts);
return _.map(combs, function(comb) {
return _.zipObject(keys, comb);
});
}
});
See working:
https://jsfiddle.net/rickysullivan/5ryf9jsa/

How to loop json array to get key and value in javascript?

I have below json array structure.. How can i get the key and value of each of the records json object?
{
"records": [{
"cfsub_2": "1",
"cf_7": "1/3/2016",
"cf_1": "Clinic San",
"cf_2": "Fever",
"cf_3": "56.60",
"cfe_8": "dsf4334"
}, {
"cfsub_2": "2",
"cf_7": "3/3/2016",
"cf_1": "Clinic Raju",
"cf_2": "braces",
"cf_3": "183.50",
"cfe_8": "fresr4"
}]
}
My expected output is to get the key and value... below as example:
<b>key</b> : cf_1, <b>value</b> : Clinic San
I have tried to loop in the records, but since i don't know the key, so i unable to get the value..
for (var z in records)
{
var value = records[z].cf_1;
alert(value);
}
//i don't know the key here.. i want to get the key and value
The full JSON structure is as below:
{
"forms": [{
"id": 1,
"records": [{
"cfsub_2": "1",
"cf_7": "1/3/2016",
"cf_1": "Clinic San",
"cf_2": "Fever",
"cf_3": "56.60",
"cfe_8": "dsf4334"
}, {
"cfsub_2": "2",
"cf_7": "3/3/2016",
"cf_1": "Clinic Raju",
"cf_2": "braces",
"cf_3": "183.50",
"cfe_8": "fresr4"
}]
}, {
"id": 7,
"records": [{
"cf_31": "27/3/2016",
"cf_32": "Singapore",
"cf_33": "dfd555",
"cfe_34": ""
}]
}, {
"id": 11,
"records": [{
"cfsub_10": "9",
"cf_9": "25/3/2016",
"cf_10": "256.50",
"cfe_11": "dfg44"
}]
}]
}
Hope this one is helpful for you.
$.each(value.forms, function(index,array){
$.each(array.records, function(ind,items){
$.each(items, function(indo,itemso){
alert( "Key -> "+indo + " : values -> " + itemso );
});
});
});
var getKeys = function (arr) {
var key, keys = [];
for (i = 0; i < arr.length; i++) {
for (key in arr[i]) {
if (arr[i].hasOwnProperty(key)) {
keys.push(key);
}
}
}
return keys;
};

JQuery: Building a dictionary with values as an array from Json

Some json data:
[
{
"country": "US",
"id": 1,
"name": "Brad",
},
{
"country": "US",
"id": 2,
"name": "Mark",
},
{
"country": "CAN",
"id": 3,
"name": "Steve",
},
]
What I'd like to do is create a dictionary from this, {country: [name id]}:
$.getJSON('result.json', function(result) {
var dict = {}
$.each(result, function(key, value){
//build dict
});
});
//{ 'US': ['Brad' 1, 'Mark' 2], 'CAN': ['Steve' 3]
What's the best way of going about this with jquery? Dictionaries constantly confound me for some reason.
$.getJSON('result.json', function(result) {
var dict = {}
$.each(result, function(key, value){
//build dict
var exists = dict[value.country];
if(!exists){
dict[value.country] = [];
}
exists.push([value.name, value.id]);
//if it was my code i would do this ...
//exists.push(value);
});
});
Personally, I don't like converting them to an array, I would keep them as values, which make them easier to manipulate.
var dict = {}
$.each(result, function(i, item){
if(!dict[item.country]) dict[item.country] = [];
dict[item.country].push([item.name, item.id]);
});
You can see this in action on this jsFiddle demo.
For the data you provided, this is the result it gives:
{"US":[["Brad",1],["Mark",2]],"CAN":[["Steve",3]]}

How to iterate through nested objects in a generic way

I am trying to fetch the value of the nested objects without using it's key. Like for example if I have a object like
var a = {"key" : "100"}
I don't want to use a.key, to get the result, though i have nested objects, it is becoming difficult for me to fetch the value this is what I have tried:
var Obj = [{"ghi":{"content":"abc"}},{"def":{"imgURL":"test.png"}},{"abc":{"key":"001"}},{"ghi":{"content":"abc"}},{"def":{"imgURL":"test.png"}},{"abc":{"key":"001"}}]
for(var key in Obj){
abc = Obj[key]
for(var j in abc){
def = abc[key]
}
}
So i need the values of all the objects, without using the key directly.
Maybe this helps
function getValues(array, key) {
var result = [];
array.forEach(function (a) {
a[key] && result.push(a[key]);
});
return result;
}
var array = [{ "ghi": { "content": "abc" } }, { "def": { "imgURL": "test.png" } }, { "abc": { "key": "001" } }, { "ghi": { "content": "abc" } }, { "def": { "imgURL": "test.png" } }, { "abc": { "key": "001" } }];
document.write('<pre>' + JSON.stringify(getValues(array, 'ghi'), 0, 4) + '</pre>');

Categories

Resources