How to covert JSON data in separate arrays in javascript? - javascript

My JSON data has following format :
[{"Name":"A","Id":"1"},{"Name":"B","Id":"2"},{"Name":"C","Id":"3"}]
How covert this into two separate arrays as Name[] and Id[] using JavaScript ?
I need the data in the following manner:
Name[0] should be : "A"
Name[1] should be : "B" and so on ...

this should work, jsonArray is your JSON
var name = [], ids = [];
jsonArray.forEach(function(item){
name.push(item.Name);
ids.push(item.Id);
}

var data = [{"Name":"A","Id":"1"},{"Name":"B","Id":"2"},{"Name":"C","Id":"3"}];
var result = {};
for (var i=0; i<data.length; i++) {
for (var key in data[i]) {
var item = data[i][key];
if (key in result)
result[key].push(item);
else
result[key] = [item];
}
}
result.Name // ["A","B","C"]
result.Id // ["1","2","3"]

You could use miso project if you are handling a lot of data with different source.
var ds = new Miso.Dataset({
data: [
{ one : 1, two : 4, three : 7 },
{ one : 2, two : 5, three : 8 }
]
}).fetch({
success: function() {
log( this.column('one').data );
}
});
http://misoproject.com/dataset/api.html#misodataset_i_fetch

Related

Remove and replace value of JSON using jquery

I am creating a heatmap in highChart. I am getting my response like datajson from a web socket. How do I make a heatmap from this json?
var datajson = [
{"type":"a","symbol":"GOO","price":"385.7110"},
{"type":"a","symbol":"ORCl","price":"444.711"},
{"type":"b","symbol":"GOO","price":"555.711"}
]
I need to get
var datajson = [
[0,0,385.7110],
[0,1,444.711],
[1,0,555.711]
]
You have not said why you are setting the 1's and 0's in the array, so there is no way for me to guess. but here is a way using Array.prototype.map to iterate over the array, modify it and get a new array back.
var datajson = [
{"type":"a","symbol":"GOO","price":"385.7110"},
{"type":"a","symbol":"ORCl","price":"444.711"},
{"type":"b","symbol":"GOO","price":"555.711"}
]
// map over the datajson array returning a new array
var result = datajson.map(item => [
item.type === 'a' ? 0 : 1,
item.symbol === 'GOO' ? 0 : 1,
item.price
])
console.log(result)
var replace = function(data) {
for (var i = 0; i < data.length; i++) {
if (data[i].type === "a") {
data[i].type = "0";
} else {
data[i].type = "1";
}
if (data[i].symbol === "GOO") {
data[i].symbol = "0";
} else {
data[i].symbol = "1";
}
}
};
var datajson = [{"type":"a","symbol":"GOO","price":"385.7110"},
{"type":"a","symbol":"ORCl","price":"444.711"},
{"type":"b","symbol":"GOO","price":"555.711"}];
replace(datajson);

compare object value with length of array in an object with javascript

EDIT: SOLVED See final solution below
EDIT: The value names are not the same
object 1
var obj1 = {
val1a : 4,
val2a : 3 ,
val3a : 7
}
object 2 with arrays
var obj2 = {
val1b : [one, two, three],
val2b : [oneA, twoA, threeA],
val3b : [oneB]
}
I am trying to do is the following
if(obj1.val1a === obj2.val1b.length){
// code
}
but I do not want it to be so specific. Is there a way to loop over each object and return the values of obj2 that do not match obj1
SOLUTION with underScore
function checkData(obj1, obj2) {
result = []
var keys_obj1 = Object.keys( obj1)
var keys_obj2 = Object.keys( obj2)
_.each(keys_obj1, function(num, i){
if(obj1[keys_obj1[i]].length !== obj2[keys_obj2[i]]) {
result.push(keys_obj1[i]);
}
})
return result;
}
The best way to do this is if both objects have the same name (for a given pair), then using The For/In Loop iterate over one of them and return the value of both, and then compare.
Remade the fiddle using Object.keys to make an array of keys for both objects, now it works even when the keys aren't the same (following the object index)
var obj1 = {
val1a : 4,
val2a : 3 ,
val3a : 7
}
var obj2 = {
val1b : ['one', 'two', 'three'],
val2b : ['oneA', 'twoA', 'threeA'],
val3b : ['oneB']
}
var keys_obj1 = Object.keys( obj1 )
var keys_obj2 = Object.keys( obj2 )
for (i = 0; i < keys_obj1.length; i++) {
console.log(keys_obj1[i]+'-'+obj1[keys_obj1[i]])
console.log(keys_obj2[i]+'-'+obj2[keys_obj2[i]].length);
if(obj1[keys_obj1[i]] === obj2[keys_obj2[i]].length) {
//match
}
}
console output :
"val1a-4"
"val1b-3"
"val2a-3"
"val2b-3"
"val3a-7"
"val3b-1"
If your model is not the definitive one, you could use an array of object like :
var object = [
{table : [one, two, three], length : 3},
{table : [one, two, three], length : 4},
... ];
and compare values using :
object[i].table.length === object[i].length
It's a little bit different from your model
but i hope it may helps.
Quite long-winded, but the only way I could think to do it:
// for each object you are going to...
function pullData(obj) {
var out = {};
var token;
// grab the keys
var keys = Object.keys(obj).map(function (el) {
// token is the character at the end of the key
// the key that is returned is the key without the token
token = el.slice(-1)
return el.slice(0, 4);
});
// for each key, add it to the output object
for (var i = 0, l = keys.length; i < l; i++) {
out[keys[i]] = obj[keys[i] + token]
}
// return an object containing the data and the token
return {data: out, token: token};
}
// take both the output from both objects being parsed
function isNotMatch(obj1, obj2) {
var out = [];
// loop over the first object using the now identical keys
for (var p in obj1.data) {
// check the values and lengths
// if they're not the same push the key and the token as a string
// to the output array
if (obj1.data[p] !== obj2.data[p].length) {
out.push(p + obj2.token);
}
}
// return the array of non-matches
return out;
}
isNotMatch(pullData(obj1), pullData(obj2));
DEMO
UPDATED:
Maybe something like this. You would have to make sure the property names are the same:
var obj1 = {
val1a : 4,
val2a : 3 ,
val3a : 7
};
var obj2 = {
val1a : ['one', 'two', 'three'],
val2a : ['oneA', 'twoA', 'threeA'],
val3a : ['oneB']
};
for(var name in obj1) {
if(obj1[name] === obj2[name].length) {
alert("match");
}
}

loop thought nested json array

I want to access salesId of json array but sales is an array also, so do loop twice?
var json = [
{
'id':1,
'sales':
[
{'salesId':123},
{'salesId':456}
]
},
{
'id':2,
'sales':
[
{'salesId':789},
{'salesId':111213}
]
}
];
for (var i in json) {
for (var j in json[i].sales) {
var result = json[i].sales[j].salesId; // here "result" will get salesId
}
}
See by yourself : here
How do you want the output?
json.map(function(x){ return x.sales.map(function(y){return y.salesId})})
returns ids per object
"[[123,456],[789,111213]]"
You can use inner loop instead, incase salesId is dynamic in sales.
for(var i=0;i<json.length;i++){
salesItem = json[i].sales;
for(var j=0;j<salesItem.length;j++){
var item = salesItem[j];
console.log(item.salesId);
}
}
If you don't care about the id you could simply flatten the array like so:
var newArray = json.reduce(function(p,c,i){
return i>1 ? p.concat(c.sales) : p.sales.concat(c.sales);
});
which will give you:
[ // newArray
{'salesId':123},
{'salesId':456},
{'salesId':789},
{'salesId':111213}
]
You could also use reduce to return just an array of salesId too if you wanted.
You don't need to loop twice
//loop through the json array that holds objects
for (var i=0; i<json.length; i++) {
var obj = json[i]; //reference to each object
var sales = obj.sales;
sales.forEach(function(element, index) {
console.log(element.salesId);
});
}
Here are two other ways. Not suggesting these are better, just 'other' ways.
var json = [
{
'id':1,
'sales':
[
{'salesId':123},
{'salesId':456}
]
},
{
'id':2,
'sales':
[
{'salesId':789},
{'salesId':111213}
]
}
];
one way:
var results = [];
for(i=0;i<json.length;i++){
results.push ( JSON.stringify(json[i].sales).match(/(\d+)/g,function($1){
return $1
}))
};
results; // [["123", "456"], ["789", "111213"]]
another way:
var str;
for(i=0;i<json.length;i++){
str = str + JSON.stringify(json[i].sales);
};
str = str.match(/(\d+)/g,function($1){
return $1
})
str; //["123", "456", "789", "111213"]

How to build a JavaScript array of key values form a json object

Basically I have the following JSON-originated Object:
({
"id" : 3,
"clientName" : "Avia",
"monthlyactiveusers" : 2083,
"dailynewlikes" : 0,
"totallikes" : 4258,
"usersgraph" : {
"sTotalLikes" : [{
"likes" : 79,
"date" : "1/1/2010"
},
{
"likes" : 116,
"date" : "1/1/2010"
}],
"sDailyActiveUsers" : [{
"likes" : 79,
"date" : "1/1/2010"
},
{
"likes" : 116,
"date" : "1/1/2010"
}]
}
});
And I need the following result:
sTotalLikes = [['1/1/2010', 79],['1/1/2010', 79],['1/11/2010', 79]];
sDailyActiveUsers = [['1/1/2010', 10],['1/5/2010', 300],['1/11/2010', 220]];
I know you can iterate through the object to build the array using the following code but I couldn't figure out how to build the JavaScript array itself. Thanks in advance for help.
var sTotalLikes = new Array();
for (var i = 0; i < usersgraph.sTotalLikes.length; i++) {
//how do I build the arry ?
sTotalLikes[i]
}
You'll have to Iteration through each item in sTotalLikes and sDailyActiveUsers.
You can also see the live demo here for complete and working program with comments. :)
// declare arrays for storing total likes and active users
var totalLikes = [];
var activeUsers = [];
// first iterate for total likes
for (var i = 0; i < data.usersgraph.sTotalLikes.length; i ++)
{
var like = data.usersgraph.sTotalLikes[i];
// create a new array of date and likes
// and push into total likes
totalLikes.push([like.date, like.likes]);
}
// then iterate for active users
for (var i = 0; i < data.usersgraph.sDailyActiveUsers.length; i ++)
{
var user = data.usersgraph.sDailyActiveUsers[i];
// create a new array of date and likes
// and push into active users
activeUsers.push([user.date, user.likes]);
}
hope this helps!
Try this.. you can easily extend it for sDailyActiveUsers
var sTotalLikes = new Array();
var lsTotalLikes = usersgraph.sTotalLikes;
for (var i = 0; i < lsTotalLikes.length; i++)
{
var obj = lsTotalLikes[i];
var lArr = []
lArr.push(obj.date);
lArr.push(obj.likes);
sTotalLikes.push(lArr)
}
It looks to me like you just want to look at the values of the objects.
var usersgraph = { ... }; // pulled from the data in your question
var result = {};
for (users_key in usersgraph) {
var vals = [];
var data = usersgraph[users_key]
for (k in data) {
vals.push(values(data[k]));
// or if you need to order them differently..
//vals.push([ data[k]['date'], data[k]['likes'] ]);
}
result[users_key] = vals;
}
Oh, if you had not guessed already you can use [] to create an array and {} to create an object/associative array.
Like this (referring to your code):
/* inside your for loop */
sTotalLikes.push([
usersgraph.sTotalLikes[i].date,
usersgraph.sTotalLikes[i].likes
])

Javascript accessing name/value pairs

I'm getting JSON name/value pairs that looks like this:
{
"Name":"parentid",
"Value":"blah"
},
{
"Name":"siteid",
"Value":"blah"
},
{
"Name":"sitename",
"Value":"blah"
}
But I would like to access the "name" value as the KEY, and the "value" value as the VALUE. Is there an elegant way to turn that piece of JSON into something like this?
{'parentid', 'blah'},
{'sitename', 'blah'}
Try this:
var items = [
{
"Name":"parentid",
"Value":"blah"
},
{
"Name":"siteid",
"Value":"blah"
},
{
"Name":"sitename",
"Value":"blah"
}
];
var results = new Object();
for (var i = 0; i < items.length; i++)
{
results[items[i].Name] = items[i].Value;
}
This will result in something like:
var results = { parentid: "Blah", siteid: "Blah", sitename: "Blah" };
One way to do it.
var json = [
{
"Name":"parentid",
"Value":"blah"
},
{
"Name":"siteid",
"Value":"blah"
},
{
"Name":"sitename",
"Value":"blah"
}
];
for ( var i = 0, l = json.length, obj; i < l; i++ )
{
obj = json[i];
json[i] = new Object();
json[i][obj.Name] = obj.Value;
}
// console.log() requires Firebug
console.log( json );
function objectflatten (array) {
var out = {}, i;
for(i = 0; i < array.length; i++) {
out[array[i].name] = array[i].value;
}
return out;
}
This is a function that will take an object in the form you presented, and output it as a "normal" object with the name values as keys, and the value values as values.
I'd recommend using the for( ... in ... ) method for this task. It'll grab the key names like you need.
var jsonObj = eval( '([{ "Name":"parentid", "Value":"blah" }])' );
for( var i = 0, assoc = {}, key; i < jsonObj.length; ++i )
{
for( key in jsonObj[ i ] ) // <-- this right here
{
assoc[ key ] = jsonObj[ i ][ key ];
}
}
and you end up with (from Firebug)
Object Name=parentid Value=blah
that can be accessed by object.key or object[ 'key' ] (in our case assoc.Name or assoc[ 'Value' ])
here's a link from Douglas Crockford from Yahoo! about using it as well - http://yuiblog.com/blog/2006/09/26/for-in-intrigue/
I'm assuming you are using PHP, and the PHP echoes you assosiatice aray like this:
echo json_encode($result);
In your javascript, you could do this:
// Soemthing retrieves php result and puts it in `var result`.
data = eval("(" + result+ ")");
alert(data.parentid);
I'm not sure if this is what you want, but it's a solution.

Categories