Retrieve values from json object - javascript

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

Related

Convert Array to JSON Array

How do I convert
["ID:2","ID:3","ID:4"]
to
[{
"ID":2
},
{
"ID":3
},
{
"ID":4
}]
because this type of data i have to send to my webservice
For getting an array with objects, you could split the strings and build a new object with the wanted property and the numerical value.
var data = ["ID:2","ID:3","ID:4"],
result = data.map(function (s) {
var p = s.split(':'),
t = {};
t[p[0]] = +p[1];
return t;
});
console.log(result);
var newArrayOfObjs =arr.map((item)=> {
var obj = {};
var splitItems = item.split(':');
obj[splitItems[0]] = splitItems[1];
return obj;
}
You'll have to split the string on ':' and set the 0th element as key and 1st element as value.
var aryExample = ["ID:2","ID:3","ID:4"], aryNew = [];
for( var i in aryExample ) {
aryNew.push({ID:Number(aryExample[i].split(":")[1])});
}
console.dir(aryNew);
That should do it.

Manipulating array to add through setData on highcharts

I have the following data:
var data = {"categories":["GLA Age: 65+"],"series":[{"name":"Hendon","data":[11.98]},{"name":"High Barnet","data":[17.86]},{"name":"Mill Hill","data":[13.73]},{"name":"Oakleigh","data":[17.42]},{"name":"Totteridge","data":[17.76]}]};
I need the 'names' to be the categories names so I'm using 'events > load' to apply this to the highcharts code:
var seriesData = this.series;
var tCategories = [];
for (i = 0; i < seriesData.length; i++) {
tCategories.push(seriesData[i].name);
}
this.xAxis[0].setCategories(tCategories);
Then I need to set the 'data' into one array like
[11.98, 17.86, 13.73, 17.42, 17.76]
The problem I've come across is that the first lot of data shows in the first bar:
example here: http://jsfiddle.net/zidski/13rexxyo/3/
The code to create the new array ([11.98, 17.86, 13.73, 17.42, 17.76])
var arrayofArrays = data.series.map(function (item) {
return JSON.stringify([item.data]);
});
var seriesString = arrayofArrays;
seriesString = seriesString;
var n = JSON.stringify(seriesString).replace(/\[|]|"/g, '');
var g = '[' + n + ']';
var h = JSON.stringify(g);
var seriesC = JSON && JSON.parse(g) || $.parseJSON(g);
this.series[0].setData(seriesC);
It seems like it's being over-complicated, if I understand correctly (though your desired outcome is not entirely clear).
You can loop through the JSON and return a data array easily enough without using stringify or anything like that, and without needing a load event:
Code:
var title = rawData.categories[0];
var chartData = []
$.each(rawData.series, function(i, node) {
chartData.push({ 'name': node.name, 'y': node.data[0] })
});
And then:
series: [{
data: chartData
}]
Updated fiddle:
http://jsfiddle.net/jlbriggs/13rexxyo/5/
Output:

Merge array of javascript objects by property key

First of all: I already found this thread, which basically is exactly what I want, but I tried my best to apply it to my needs - I couldn't.
So, I have the following javascript function:
function loadRelationData(object) {
var result = [];
var parents = []
parents = getParentObjectsByObjectID(object['ObjectID']);
var tmpFirstObjects = [];
var tmpOtherObjects = [];
$.each(parents, function (_, parent) {
var keyName = 'Übergeordnete ' + parent['ObjectType'];
var pushObject = {};
if (parent['ObjectType'] == object['ObjectType']) {
pushObject['Fieldname'] = keyName;
pushObject['Value'] = parent['Name'];
tmpFirstObjects.push(pushObject);
} else {
pushObject['Fieldname'] = keyName;
pushObject['Value'] = parent['Name'];
tmpOtherObjects.push(pushObject);
}
});
result = result.concat(tmpFirstObjects).concat(tmpOtherObjects);
return result;
}
The parents array looks like this
And my function creates this result
This might be a bit complicated, but I need to split it up like this, because I need the order.
What I want is an array with both "TEC_MapLocations" joined together like this:
[
{Fieldname: 'Übergeordnete TEC_Equipment', Value: 'E0192'},
{Fieldname: 'Übergeordnete TEC_MapLocation', Value: ['M100', 'M200']},
{Fieldname: 'Übergeordnete TEC_FunctionalLocation', Value: 'FL456'}
]
Any ideas on how to alter my code to achieve the desired result right away or how to merge the results array?
edit: I used Joseph's solution and used the following (quick and dirty) sort function to get back my desired sorting:
output.sort(function (a, b) {
if (a.ObjectType == object.ObjectType) {
return -1
} else {
return 1
}
});
What you'd want to do first is build a hash with Fieldname as key, and an array as value. Then you'd want to use reduce to add the values into the hash and array. Then you can transform it into an array using Object.keys and map.
var input = [
{Name: 'M100', ObjectID: 1, ObjectType: 'TEC_MapLocation'},
{Name: 'M200', ObjectID: 2, ObjectType: 'TEC_MapLocation'},
{Name: 'FL456', ObjectID: 4, ObjectType: 'TEC_FunctionalLocation'},
{Name: 'E0192', ObjectID: 5, ObjectType: 'TEC_Equipment'}
];
var hash = input.reduce(function(carry, item){
// Create the name
var name = 'Übergeordnete ' + item.ObjectType;
// If array with name doesn't exist, create it
if(!carry[name]) carry[name] = [];
// If item isn't in the array, add it.
if(!~carry[name].indexOf(item.Name)) carry[name].push(item.Name);
return carry;
}, {});
// Convert the hash into an array
var output = Object.keys(hash).map(function(key, index, array){
return { Fieldname: key, Value: hash[key] }
});
document.write(JSON.stringify(output));
Try this:
function joinObjects( array ) {
// Start with empty array
var ret = new Array();
// Iterate array
for ( var i = 0; i < array.length; i++ ) {
// Search by fieldname
var match = false;
var j;
for ( j = 0; j < ret.length; j++ ) {
if ( array[i].Fieldname == ret[j].Fieldname ) { match = true; break; }
}
// If not exists
if ( !match ) {
// Intert object
ret.push({
Fieldname: array[i].Fieldname,
Value: new Array()
});
}
// Insert value
ret[j].Value.push( array[i].Value );
}
// Return new array
return ret;
}
http://jsfiddle.net/6entfv4x/

How to convert JSON data to Array in JQuery?

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

How can I find which index in an array contains an object whose value for a specific key is x? [duplicate]

I would like to find index in array. Positions in array are objects, and I want to filter on their properties. I know which keys I want to filter and their values. Problem is to get index of array which meets the criteria.
For now I made code to filter data and gives me back object data, but not index of array.
var data = [
{
"text":"one","siteid":"1","chid":"default","userid":"8","time":1374156747
},
{
"text":"two","siteid":"1","chid":"default","userid":"7","time":1374156735
}
];
var filterparams = {userid:'7', chid: 'default'};
function getIndexOfArray(thelist, props){
var pnames = _.keys(props)
return _.find(thelist, function(obj){
return _.all(pnames, function(pname){return obj[pname] == props[pname]})
})};
var check = getIndexOfArray(data, filterparams ); // Want to get '2', not key => val
Using Lo-Dash in place of underscore you can do it pretty easily with _.findIndex().
var index = _.findIndex(array, { userid: '7', chid: 'default' })
here is thefiddle hope it helps you
for(var intIndex=0;intIndex < data.length; intIndex++){
eachobj = data[intIndex];
var flag = true;
for (var k in filterparams) {
if (eachobj.hasOwnProperty(k)) {
if(eachobj[k].toString() != filterparams[k].toString()){
flag = false;
}
}
}
if(flag){
alert(intIndex);
}
}
I'm not sure, but I think that this is what you need:
var data = [{
"text":"one","siteid":"1","chid":"default","userid":"8","time":1374156747
}, {
"text":"two","siteid":"1","chid":"default","userid":"7","time":1374156735
}];
var filterparams = {userid:'7', chid: 'default'};
var index = data.indexOf( _.findWhere( data, filterparams ) );
I don't think you need underscore for that just regular ole js - hope this is what you are looking for
var data = [
{
"text":"one","siteid":"1","chid":"default","userid":"8","time":1374156747
},
{
"text":"two","siteid":"1","chid":"default","userid":"7","time":1374156735
}
];
var userid = "userid"
var filterparams = {userid:'7', chid: 'default'};
var index;
for (i=0; i < data.length; i++) {
for (prop in data[i]) {
if ((prop === userid) && (data[i]['userid'] === filterparams.userid)) {
index = i
}
}
}
alert(index);

Categories

Resources