How to convert JSON data to Array in JQuery? - javascript

I am getting Json data from result as following,
var chartData1 = [
{\"Action\":\"Twitter\",\"value\":\"1.00\",\"platform\":\"2\"},
{\"Action\":\"WhatsApp\",\"value\":\"1.00\",\"platform\":\"3\"},
{\"Action\":\"Messaging\",\"value\":\"1.00\",\"platform\":\"4\"}
]
I want to convert it to following,
var chartData2 = [
['Action', 'value', 'platform'],
['Twitter', '1.00', 2],
['WhatsApp', '1.00', 3],
['Messaging', 'WhatsApp', 4],
]
I have used different methods like parseJSON,map,etc , but i could not get expected results.
Can you help me out from this.

I'm assuming you first need to parse valid JSON string containing your data and then convert each row with object to array. And prepend whole array with array with column names. Following code will exactly do that:
var chartDataString = "[{\"Action\":\"Twitter\",\"value\":\"1.00\",\"platform\":\"2\"},{\"Action\":\"WhatsApp\",\"value\":\"1.00\",\"platform\":\"3\"},{\"Action\":\"Messaging\",\"value\":\"1.00\",\"platform\":\"4\"}]";
var chartData = JSON.parse(chartDataString);
var keys = [];
var data = [];
var row;
for (var i = 0; i < chartData.length; i++) {
row = [];
for (var key in chartData[i]) {
if (i === 0) {
keys.push(key);
}
row.push(chartData[i][key]);
}
if (i === 0) {
data.push(keys);
}
data.push(row);
}
console.log(data);

The following will convert it to an array, providing that it is already parsed as an object.
var chartData2 = Object.keys(chartData1).map(function(k) { return chartData1[k] });
console.log(chartData2);

Probably the most ideal here is to map original array to new structure:
var chartData1 = [
{"Action":"Twitter","value":"1.00","platform":"2"},
{"Action":"WhatsApp","value":"1.00","platform":"3"},
{"Action":"Messaging","value":"1.00","platform":"4"}
];
var result = chartData1.map(function(el) {
return [el.Action, el.value, el.platform];
});
result.unshift(['Action', 'value', 'platform']);
alert(JSON.stringify(result, null, 4));

Related

push values from array of objects into new array

I have data such as
var data = [{"2013-01-21":1,"2013-01-22":7},{"2014-01-21":2,"2014-01-22":8}];
Now i need output as new
data = [ [1,7],[2,8] ]
My code outputs [1,2,7,8] , i need as [[1,2],[7,8]].
var data = [{
"2013-01-21": 1,
"2013-01-22": 7
}, {
"2014-01-21": 2,
"2014-01-22": 8
}];
//document.write(data.length)
var result = [];
for (var i = 0; i < data.length; ++i) {
var json = data[i];
console.log(json)
for (var prop in json) {
result.push(json[prop]);
console.log(json[prop])
// or myArray.push(json[prop]) or whatever you want
}
}
$('#result').html(JSON.stringify(result));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="result"></div>
You need to create a nested array in the for loop.
But there's a built-in function Object.values() that will get what you want.
var data = [{
"2013-01-21": 1,
"2013-01-22": 7
}, {
"2014-01-21": 2,
"2014-01-22": 8
}];
var results = data.map(obj => Object.values(obj));
console.log(results);
Object.values() gives you the values in each object. And you need to iterate over an array of objects, so:
var data = [{"2013-01-21":1,"2013-01-22":7},{"2014-01-21":2,"2014-01-22":8}];
// data = [ [1,7],[2,8] ]
const extracted = data.map( obj => Object.values(obj))
console.log(extracted)
Object.values()
var data = [{
"2013-01-21": 1,
"2013-01-22": 7
}, {
"2014-01-21": 2,
"2014-01-22": 8
}];
var result = [];
for (var i = 0; i < data.length; i++) {
result.push(Object.values(data[i]));
}
$('#result').html(JSON.stringify(result));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="result"></div>
From MDN - The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop.
This is exactly what you need.
var data = [{"2013-01-21":1,"2013-01-22":7},{"2014-01-21":2,"2014-01-22":8}];
const arr = data.map(x => Object.values(x));
console.log(arr);
You can get values array by using Object.values()
Solution will be like this:
const data = [{ "2013-01-21": 1, "2013-01-22": 7 }, { "2014-01-21": 2, "2014-01-22": 8 }];
const output = data.map(e => Object.values(e) )
console.log(output)

Retrieve values from json object

I have a JSON object that is structrued like the following ...
[{"staffId":4,"forename":"Testf","surname":"Tests","location":"Testl","phoneNumber":"00000000000","email":"Teste"}]
Can anyone advise how I would retrieve the keys and values and add to Arrays in JavaScript or JQuery. For Example ...
var headings = ["staffId","forename","surname"];
var staff = [["1","Joe","Bloggs"],["2","Stack","Overflow"]];
for one such JSON object it will be
var json = [{"staffId":4,"forename":"Testf","surname":"Tests","location":"Testl","phoneNumber":"00000000000","email":"Teste"}];
var headings = Object.keys(json[0]);
var staff = [];
for ( var key in json[0] )
{
staff.push( json[0][ key ] );
}
console.log( headings );
console.log( staff );
for multiple, you need to iterate them like
for ( var counter = 0; counter < json.length; counter++ )
{
var jsonObj = json[ counter ];
//same code for all json objects as above
}
If I understand correctly, you want to do something like this:
var data = [
{
'staffId': 1,
'forename': 'Joe',
'surname': 'Bloggs',
'location': 'Testl1',
'phoneNumber': '0770....',
'email': 'Teste1'
},
{
'staffId': 4,
'forename': 'Testf',
'surname': 'Tests',
'location': 'Testl',
'phoneNumber': '07702671940',
'email': 'Teste'
}
];
var headings = ["staffId","forename","surname"];
var result = data.map(function(item) {
return headings.map(function(heading) {
return item[heading];
});
});
console.log(result);
you can map/transform your array using Array.prototype.map().
You can parse the Json with jQuery
var json = $.parseJSON(data);
The call the values
alert(json.name);

array object manipulation to create new object

var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var expect = [
{month:"JAN",val: {"UK":"24","AUSTRIA":"64","ITALY":"21"}},
{month:"FEB",val: {"UK":"14","AUSTRIA":"24","ITALY":"22"}},
{month:"MAR",val: {"UK":"56","AUSTRIA":"24","ITALY":"51"}}
];
I have array of objects which i need to reshape for one other work. need some manipulation which will convert by one function. I have created plunker https://jsbin.com/himawakaju/edit?html,js,console,output
Main factors are Month, Country and its "AC" value.
Loop through, make an object and than loop through to make your array
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var outTemp = {};
actual.forEach(function(obj){ //loop through array
//see if we saw the month already, if not create it
if(!outTemp[obj.month]) outTemp[obj.month] = { month : obj.month, val: {} };
outTemp[obj.month].val[obj.country] = obj.AC; //add the country with value
});
var expected = []; //convert the object to the array format that was expected
for (var p in outTemp) {
expected.push(outTemp[p]);
}
console.log(expected);
Iterate through array and create new list
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var newList =[], val;
for(var i=0; i < actual.length; i+=3){
val = {};
val[actual[i].country] = actual[i]["AC"];
val[actual[i+1].country] = actual[i+1]["AC"];
val[actual[i+2].country] = actual[i+2]["AC"];
newList.push({month: actual[i].month, val:val})
}
document.body.innerHTML = JSON.stringify(newList);
This is the correct code... as above solution will help you if there are 3 rows and these will be in same sequnece.
Here is perfect solution :
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var tmpArray = [];
var obj =[];
for(var k=0; k<actual.length; k++){
var position = tmpArray.indexOf(actual[k].month);
if(position == -1){
tmpArray.push(actual[k].month);
val = {};
for(var i=0; i<actual.length; i++){
if(actual[i].month == actual[k].month){
val[actual[i].country] = actual[i]["AC"];
}
}
obj.push({month: actual[k].month, val:val});
}
}

How do I do a array group and count it, like in MySQL group by given column id?

I have a large array as bellow, now I need to do a group by first column and count the total of that channel existence.
For example:
var original_db = [
["channel1", "online"],
["channel2", "offline"],
["channel3", "online"],
["channel1", "online"],
["lot more"]....
]
Expected result from the original result need to be:
var custom_db = [
["channel1", 2],
["channel2", 0],
["channel3", 1]
]
EDIT:
for(var key in original_db) {
var i;
for (i = 0; i < original_db.length; i += 1) {
if (original_db[i][0] === original_db[key][0]) {
original_db.splice(i, 1);
return;
}
}
}
console.log(original_db);
Use an object whose properties are the first elements to keep the count:
var counts = {};
for (var i = 0; i < original.length; i++) {
var key = original[i][0];
if (counts[key]) {
counts[key]++;
} else {
counts[key] = 1;
}
}
You can then turn this into your final array, although I'm not sure why you prefer that over the counts object:
final = [];
for (var key in counts){
final.push([key, counts[key]]);
}
Convert the array to JSON object and do a loop to get the count.
I don't know if there is a group by, order by in javascript but what you can do create a new array and check if the indexes of channels are set. If it is set, you increment it. If it is not set, and the status is online, you set it to 1, otherwise to 0;
var original_db = [
["channel1", "online"],
["channel2", "offline"],
["channel3", "online"],
["channel1", "online"]
];
var ordered_arr = {};
for(var i=0;i<original_db.length;i++)
{
if(ordered_arr[original_db[i][0]])
ordered_arr[original_db[i][0]]+=1;
else
if(original_db[i][1] =="online")
ordered_arr[original_db[i][0]]=1;
else
ordered_arr[original_db[i][0]]=0;
}
console.log(ordered_arr);

Setting up a variable length two-dimensional array

I have a string as follows :
Panther^Pink,Green,Yellow|Dog^Hot,Top
This string means I have 2 main blocks(separated by a '|') :
"Panther" and "Dog"
Under these two main blocks, I have, lets say "subcategories".
I wanted to create a 2-dimensional array represented (in logic) as follows :
Panther(Array 1) => Pink(Element 1),Green(Element 2), Yellow(Element 3)
Dog(Array 2) => Hot(Element 1), Top(Element 2)
Also,I want to be able to add a main block, lets say "Cat" with possible categories "Cute,Proud" to the two dimensional array
I've managed to get an Array containing "Panther^Pink,Green,Yellow" and "Dog^Hot,Top" by using JavaScript's split function.
Note that this string is received via Ajax and can be of any length, though the format shown above is always used.
----------------------------- EDIT ----------------------------
Ok, my script so far is :
$(document).ready(function(){
appFunc.setNoOfAppBlock('Panther^Pink,Green,Yellow|Dog^Hot,Top');
appFunc.alertPing();
});
var appFunc = (function(stringWithSeper) {
var result = {},
i,
categories = new Array(),
subcategories;
return {
setNoOfAppBlock: function(stringWithSeper){
categories = stringWithSeper.split("|");
for (i = 0; i < categories.length; i++) {
subcategories = categories[i].split("^");
result[subcategories[0]] = subcategories[1].split(",");
}
},
alertPing: function(){
alert(result["Panther"][1]);
}
};
})();
However, the function "alertPing" isn't "alerting" anything.What am am I doing wrong ?
To me the most logical representation of your data:
Panther^Pink,Green,Yellow|Dog^Hot,Top
Is with a JavaScript object with a property for each category, each of which is an array with the subcategories:
var data = {
Panther : ["Pink", "Green", "Yellow"],
Dog : ["Hot", "Top"]
}
You would then access that by saying, e.g., data["Dog"][1] (gives "Top").
If that format is acceptable to you then you could parse it as follows:
function parseData(data) {
var result = {},
i,
categories = data.split("|"),
subcategories;
for (i = 0; i < categories.length; i++) {
subcategories = categories[i].split("^");
result[subcategories[0]] = subcategories[1].split(",");
}
return result;
}
var str = "Panther^Pink,Green,Yellow|Dog^Hot,Top";
var data = parseData(str);
Assuming you're trying to parse your data into something like this:
var result = {
Panther: ["Pink", "Green", "Yellow"],
Dog: ["Hot", "Top"]
}
you can use string.split() to break up your string into subarrays:
var str = "Panther^Pink,Green,Yellow|Dog^Hot,Top";
var result = {}, temp;
var blocks = str.split("|");
for (var i = 0; i < blocks.length; i++) {
temp = blocks[i].split("^");
result[temp[0]] = temp[1].split(",");
}
Data can then be added to that data structure like this:
result["Cat"] = ["Cute", "Proud"];
Data can be read from that data structure like this:
var dogItems = result["Dog"]; // gives you an array ["Hot", "Top"]
You can use something like:
function parseInput(_input) {
var output = [];
var parts = _input.split('|');
var part;
for(var i=0; i<parts.length; i++) {
part = parts[i].split('^');
output[part[0]] = part[1].split(',');
}
return output;
}
Calling parseInput('Panther^Pink,Green,Yellow|Dog^Hot,Top'); will return:
output [
"Panther" => [ "Pink", "Green", "Yellow" ],
"Dog" => [ "Hot", "Top" ]
]
To add another item to the list, you can use:
output["Cat"] = ["Cute", "Proud"];

Categories

Resources