how to get left side data of a json dynamically - javascript

I have a json which is like
{
"Payload":[{
"PrevYr":"21333",
"CurYr":"123454"
},{
"PrevYr":"234333",
"CurYr":"45546"
},{
"PrevYr":"3563",
"CurYr":"67854"
}]
}
Now in my code i read this json using
$.getJSON("readJson.json", function (data) {}
I need to read the json and create another json with some changes on it. But i can't read the "CurYr" and "PrevYr". I mean not their values. But them. So if there is 2014 and 2015 in place of curyr and prevyr i can get them also. I need to read the left side. Please help..

Try something like this,
var test = {
"Payload":[{
"PrevYr":"21333",
"CurYr":"123454"
},{
"PrevYr":"234333",
"CurYr":"45546"
},{
"PrevYr":"3563",
"CurYr":"67854"
}]};
$.each(test.Payload,function(key,val){
$.each(val,function(key1,val1){
alert(key1);
});
});
or
var keySet = Object.keys( test.Payload[0] );
alert( keySet[0]);
alert( keySet[1]);

you can use Object.keys( obj );
try
$.getJSON("readJson.json", function (data) {
console.log( Object.keys(data.Payload[0]));
}

try this:
var obj = {
"Payload":[{
"PrevYr":"21333",
"CurYr":"123454"
},{
"PrevYr":"234333",
"CurYr":"45546"
},{
"PrevYr":"3563",
"CurYr":"67854"
}]
}
var objKeys = Object.keys(obj);
objKeys.forEach(function(key){
// This returns "Payload"
var _innerKeys = Object.keys(obj[key]);
// This returns "0,1,2" since obj[key] is an array.
_innerKeys.forEach(function(k){
// This will return "PrevYr, CurYr"
var _innerProp = Object.keys(obj[key][k]);
console.log(_innerProp);
})
console.log("Inner Keys: ", _innerKeys);
})

Related

How to save data in json format?

I created a program that receives data from four channels.
This is the type of data.
( 0.499147;0.499147;0.499147;0.499147; )
(Separated by ';') Data can be read every interval set up to 100 times.
So I want to save the received data in JSON format.
I wrote the following code but could not save it in JSON format.
port.on('data',function(devicevalue){
arrayvalue = devicevalue.toString();
eachvalue = arrayvalue.split(';');
ch0value = eachvalue[0];
ch1value = eachvalue[1];
ch2value = eachvalue[2];
ch3value = eachvalue[3];
var json_data =
{
index : i ,
ch0value : eachvalue[0],
ch1value : eachvalue[1],
ch2value : eachvalue[2],
ch3value : eachvalue[3],
};
Later if i write this code
jsonfile.writeFile(file,json_data,{flag: 'a', spaces: 2},function(err){
console.error(err)
});
[https://i.stack.imgur.com/DMc5M.png][https://i.stack.imgur.com/DMc5M.png]
If i write this instead of the above
var objjson = JSON.stringify(json_data);
jsonfile.writeFile(file,objjson,{flag: 'a', spaces: 2},function(err){
console.error(err)
});
[ https://i.stack.imgur.com/8ldPG.png][https://i.stack.imgur.com/8ldPG.png]
If I want this form, how do I write the code?
[https://i.stack.imgur.com/nEr3e.png][https://i.stack.imgur.com/nEr3e.png]
How about this:
var results = [];
var i = 0;
port.on('data', function(devicevalue) {
var newElement = {
index: i,
ch0value: eachvalue[0],
ch1value: eachvalue[1],
ch2value: eachvalue[2],
ch3value: eachvalue[3],
ch4value: eachvalue[4]
};
results.push(newElement);
i++;
});
port.on('close', function(code, signal) {
jsonfile.writeFile(file,results,{flag: 'a', spaces: 2}, console.log);
});
Try using toJS().
example: var.toJS();
You can also try toJSON. Same concept, but toJS returns a deeply copied version of the object.

Comparing Javascript Objects by their ID to create a unique list in Angular/JS

I have a call to the github API that gives me a an array of objects containing their commits. I want to loop through this and get a unique list of commitors and build it in the format:
{"id":temp,"label":temp,"type": "number","p": {} }
so I can graph it.
I wrote the following:
$scope.git = response.data;
$scope.o=[];
angular.forEach($scope.git,function(value){
var temp = value.commit.author.name;
if($scope.o.length==0){
$scope.o.push({"id":temp,"label":temp,"type": "number",
"p": {}
})
}
else{
angular.forEach($scope.o,function(ob){
if(ob.id==temp){
continue;
}
else{
$scope.o.push({"id":temp,"label":temp,"type": "number",
"p": {}
})
}
});
}
})
This works but it is horribly inefficient. What's the right way to do this?
You can use an object to check if an author has been already inserted into the list. Something like:
$scope.o = [];
var authors = {};
angular.forEach($scope.git, function(value){
var temp = value.commit.author.name;
if (authors[temp] === undefined) {
$scope.o.push({"id":temp,"label":temp,"type": "number", "p": {} });
authors[temp] = true;
}
});
you can also use libraries like underscore or lodash.one of the method that would be helpful here will be _.uniqBy.Here is the documentation for the same
https://lodash.com/docs/4.17.4#uniqBy

MongoDB Node JS - to delete an entry from an object inside a document object

I'm trying to create a command in Node JS using native mongodb driver, to remove the key value pair from an object which is inside the document object.
I have a mongoDB collection in the following format:
{
"name" : "PrakashPM"
"data" : {
"Jan-2017" : "2,3,1",
"Dec-2016" : "1,2,0",
"Nov-2016" : "9,9,9"
}
},
{
"name" : "Valavan"
"data" : {
"Jan-2017" : "1,1,1",
"Dec-2016" : "3,3,3",
"Nov-2016" : "9,9,9"
}
}
My target is to remove "Dec-2016" : "1,2,0" which is inside "name" :
"PrakashPM"
My Code:
var mongoName = 'PrakashPM';
var mongoDate = "'data'.'Dec-2016'";
// TRIALS
// var mongoDate = "data.'Dec-2016'";
// var mongoDate = "data.Dec-2016";
var mongoVal = "'1,2,0'";
// TRIALS
// var mongoVal = "1,2,0";
mycollection.update( { name: mongoName },
{ $unset: {mongoDate : mongoVal} }
);
NOTE: I'm doing the above operations inside a PUT request function.
I tried many possible ways (TRIALS) for the input values (mongoDate, mongoVal) but I'm not able to achieve the result below.
Also, is it possible to remove the key value pair entry, just by using the key? (i.e. in this case {$unset: {mongoDate}} or something like that)
EXPECTED RESULT:
{
"name" : "PrakashPM"
"data" : {
"Jan-2017" : "2,3,1",
"Nov-2016" : "9,9,9"
}
},
{
"name" : "Valavan"
"data" : {
"Jan-2017" : "1,1,1",
"Dec-2016" : "3,3,3",
"Nov-2016" : "9,9,9"
}
}
Assuming that req.body.timerDate has the month-date string value exactly as in MongoDB, this should work. (See documentation).
You have to use string as key. You cannot use variable names there.
// Assuming that req.body.timerDate
// has the month-date as stored in MongoDB (case-sensitive match)
var reqDate = "data." + req.body.timerDate;
var reqName = req.body.name;
var _unset = {};
_unset[reqDate] = "";
mycollection.update({ name: reqName }, { $unset: _unset })
Use the following example as a guide to updating your collection. You need to use the bracket notation to create your query and update documents i.e. you require an update operation which has the structure:
db.mycollection.update(
{ 'name': 'PrakashPM' },
{
'$unset': {
'data.Dec-2016': ''
}
}
)
So, using the variables to construct the objects to use in your operation
var mongoName = 'PrakashPM';
var timerDate = 'Dec-2016';
var query = {};
var update = {'$unset': {}};
query['name'] = mongoName;
update['$unset']['data.'+timerDate] = '';
db.mycollection.update(query, update)
You are trying to use variables as keys in a object.
mycollection.update( { timerName: mongoName },
{ $unset: {mongoDate : mongoVal} }
);
This does not work as you expect and is a general JavaScript concept (not mongodb problem).
You are sending a query to mongo to update a row where the key "timerName" equals the content of the variable "mongoName".
But the proper key is "name".
Try this:
mycollection.update( { name: mongoName },
{ $unset: {data : mongoVal} }
);

How to convert object key dot notation to object tree in javascript

I have a form and I want to send it to an ajax endpoint, for this I have this helper method:
$.fn.serializeFormToObject = function() {
//serialize to array
var data = $(this).serializeArray();
//add also disabled items
$(':disabled[name]', this)
.each(function() {
data.push({ name: this.name, value: $(this).val() });
});
//map to object
var obj = {};
data.map(function(x) { obj[x.name] = x.value; });
return obj;
};
The problem is that I have dot notation in some of the names of my form (using MVC strong typed model)
So I have this object as result:
Task.Addresses.Box:""
Task.Addresses.City:"Limal"
Task.Addresses.Country:"Belgique"
Task.Deadline:"1/10/2017 12:18:18 PM"
Task.TaskSourceId:"1"
And the result expected would be:
{ Task : { Addresses: { Box: "", City: "Limal", Country: "Belgique"}, Deadline: "1/10/2017 12:18:18 PM", TaskSourceId:"1" } }
I use the lodash library but after some hours I cannot find a way to do this expected result.
Can someone provide me a working javascript helper to give the expected nested object?
Edit:
For duplicated question, the other question does not ask about combined nested object together
After the answer of #ori-drori, This code is working as expected:
$.fn.serializeFormToObject = function() {
//serialize to array
var data = $(this).serializeArray();
//add also disabled items
$(':disabled[name]', this)
.each(function() {
data.push({ name: this.name, value: $(this).val() });
});
//map to object
var obj = {};
data.map(function (x) { obj[x.name] = x.value; });
var objNested = {};
_.forEach(obj, function (value, key) { _.set(objNested, key, value) });
return objNested;
};
Iterate the data using Array#forEach, and assign the value to the path (name) using _.set():
data.forEach(function(x) { _.set(obj, x.name, x.value) });
I don't have you're original data, so here is a demo using the key-values you provided.
var fields = {
"Task.Addresses.Box": "",
"Task.Addresses.City": "Limal",
"Task.Addresses.Country": "Belgique",
"Task.Deadline": "1/10/2017 12:18:18 PM",
"Task.TaskSourceId": "1"
};
var obj = {};
_.forEach(fields, function(value, key) {
_.set(obj, key, value);
});
console.log(obj);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Format returned table data in json

I'm fairly new to javascript. I retreive data from a sql server database that looks like this :
[Object { shortcode="0013A2004031AC9A", latest_measurement=1067, keyid="6801"},
Object { shortcode="0013A2004031AC9A", latest_measurement=7, keyid="6802"},
Object { shortcode="0013A2004031AC9A", latest_measurement=8598838, keyid="6803"}]
I want to format this in a json like this :
{mac : 0013A2004031AC9A, keys : {6801:1067, 6802:7, 6803:8598838}}
but I just don't get to that.
I have
var jsonDataPerMac = {};
I loop over the json object above and for every new mac I find I do :
jsonDataPerMac[i]={"mac": device.shortcode, "keys":[]};
but how do I get to fill the keys?
Any hints would be appreciated.enter code here
var macs = [];
var jsonDataPerMac = {};
var i = 0;
$.ajax({
url: "/bmmeasurements",
type: "GET",
data: {"unitid" : unitid},
async: false,
success: function (data) {
console.log(data);
initializeTable();
$.each(data, function (index,device) {
//add all distinct macs in an array, to use them as a column header
if($.inArray(device.shortcode, macs) == -1) {
macs.push(device.shortcode);
jsonDataPerMac[i]={"mac": device.shortcode, "keys":[]};
i++;
//create a table cell for each possible key. id = 'mac-key'
createTableGrid(device.shortcode);
}
//add the measurement data to the correct cell in the grid
$('#' + device.shortcode + '-' + device.keyid).html(device.latest_measurement);
});
}});
Here is my proposition. I would rather avoid using jQuery to perform such a simple operations. In this particular example, we use forEach and for..in loop.
//new output array
var newArray = [];
//we traverse the array received from AJAX call
array.forEach(function(el) {
var added = false; // it's false by default
// we check if the mac is already in newArray, if yes - just add the key
for(var i in newArray) {
if(newArray[i].mac == el.shortcode) {
newArray[i].keys.push(el.keyid+":"+el.latest_measurement);
added = true; // tells us whether the key has been added or not
}
}
// if key hasn't been added - create a new entry
if(!added) {
newArray.push({"mac": el.shortcode, "keys":[el.keyid+":"+el.latest_measurement]});
}
});
console.log(newArray);
You can transform above code to a function and then, reuse it in your ajax onSuccess method. Remember to pass the array as an argument and to return newArray.
JSFiddle:
http://jsfiddle.net/2d5Vq/2/
You need to combine the entries first...
var reducedData = {};
$.each(macs, function(index,macitem){
if (reducedData.hasOwnProperty(macitem.shortcode)) {
reducedData[macitem.shortcode].push(macitem.key);
} else {
reducedData[macitem.shortcode] = [ macitem.key ];
}
});
And then map to your desired format inside an array...
var jsonDataPerMac = [],
i = 0;
$.map(reducedData, function(keys,mac){
jsonDataPerMac[i++] = {"mac": mac, "keys": keys};
// your other code goes here
});
Also your usage of jsonDataPerMac suggests that you want it to be an array.

Categories

Resources