How to console the JSON.Stringify result [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
<script>
$.getJSON('url/rest/1', function (data) {
var mydata = JSON.stringify(data);
});
</script>
This is my code. For console.log(mydata) my output is :
{
"data":[
{
"orderid":"9",
"ordercode":"TTG-13-06-3"
},
{
"orderid":"12",
"ordercode":"TTG-13-06-4"
},
{
"orderid":"15",
"ordercode":"TTG-13-06-5"
},
{
"orderid":"20",
"ordercode":"TTG-13-06-6"
},
{
"orderid":"24",
"ordercode":"TTG-13-06-7"
},
{
"orderid":"26",
"ordercode":"TTG-13-06-8"
},
{
"orderid":"31",
"ordercode":"TTG-13-06-9"
},
{
"orderid":"36",
"ordercode":"TTG-13-06-10"
},
{
"orderid":"41",
"ordercode":"TTG-13-06-11"
},
{
"orderid":"44",
"ordercode":"TTG-13-06-12"
}
],
"status":"success"
}
I need to get ordercode alone in console. How can I achive it?

Use $.map to transform each object in your collection:
var orderCodes = $.map(data.data, function(entry){
return entry.ordercode;
});
and get an array of all ordercodes.
See: http://api.jquery.com/jquery.map/
If you're using any sort of functional programming library (i.e. underscore) this operation is usually abstracted into a method called pluck: http://underscorejs.org/#pluck

Use each of jQuery
$.each(data.data,function(index,value){
console.log(value.overcode)
})

The return data is array of objects, thus we need to loop through it to retrieve ordercode property.
var mydata = JSON.stringify(data);
// Check if mydata object has "data" property before looping
if(mydata.hasOwnProperty(data)) {
for(var i = 0; i < mydata.data.length; i++) {
console.log(mydata.data[i].ordercode);
}
}

$.each(myData.data, function (i, obj) {
console.log(obj.ordercode);
});

Second using foreach-
var parsedMyData = JSON.parse(mydata);
var arr = [];
for(i in parsedMyData) {
arr.push(parsedMyData[i].ordercode);
}
console.log(arr);
o/p- ["TTG-13-06-3", "TTG-13-06-4", "TTG-13-06-5".....]

Best and shortest option-
var data=JSON.stringify(mydata);
$.map(data, function(value){
console.log(value.ordercode);
});

First option -
var parsedMyData = JSON.parse(mydata);
var objectForConsole = $.extend({}, $.map(parsedMyData, function(val) {return val.ordercode; }));
console.log(objectForConsole);
This will print: Object {0: "TTG-13-06-3", 1: "TTG-13-06-4"....}

Related

How do i restructure following code? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I want to create an json structure with data which will get from an api call. I can generate the structure by using following code. But how can I restructure the code to remove nested call of function and loops.
var temp = {
applications: []
};
api.getApplications(conceptId)
.then((applications) => {
for (var i = 0; i < applications.length; i++) {
(function(indexOfAppArr) {
let applicationId = applications[indexOfAppArr].id;
temp.applications.push({
id: applicationId,
databases: []
});
api.getDbs(conceptId, applicationId)
.then(databases => {
for (var j = 0; j < databases.length; j++) {
(function(indexOfDatabasArr) {
let databaseid = databases[indexOfDatabasArr].id;
temp.applications[indexOfAppArr].databases.push({
id: databaseid,
tabels: []
});
api.
getSchema(conceptId,
applicationId, databaseid).
then(function(schemas) {
for (var k = 0; k < schemas.length; k++) {
(function(indexofschemaarr) {
let schemaid = schemas[indexofschemaarr].id;
api.getTable(conceptId, schemaid)
.then(function(tables) {
console.log(tables);
})
})(k)
}
})
})(j)
}
})
})(i)
}
})
Here is the JSON structure which i want to create.
{
applications:[{
id:'',
databases:[{
id:'',
tabels:[
{
id:'',
columnId:''
}
]
}]
}]
};
If you read a little you'll actually learn how to do it. I personally haven't had the need to learn it yet but it sounded interesting, here is an excellent website that I found for you:
https://javascript.info/promise-chaining
it explains there how to "restructure" the code you are asking by putting it in less words:
loadScript("/article/promise-chaining/one.js").then(function(script1) {
loadScript("/article/promise-chaining/two.js").then(function(script2) {
loadScript("/article/promise-chaining/three.js").then(function(script3) {
// this function has access to variables script1, script2 and script3
one();
two();
three();
});
});
});
I'm sure it only takes less than 30 mts of reading. Best of luck!

how to remove the chrome.storage.local

Im not getting how remove chrome.storage.local values in javascript?
i use like this but the storage value is not removing from the store:chrome.storage.local.remove(result.MyFile.Base64File);
Please check the below code, here I'm using chrome.storage.local.set to set
var obj = { DocName: "name", Base64File: "Base64string" };
chrome.storage.local.set({ 'MyFile': obj });
and chrome.storage.local.get to retrive the values
chrome.storage.local.get('MyFile', function (result) {
var PdfBase64 = result.MyFile.Base64File;
var DocumentName = result.MyFile.DocName;
}
Note: You can not remove values, you can remove indexes with specific names what causes that they gets removed WITH there values.
Tbh I could not run the code but I'm pretty sure something like this should work. But I really recommend you to avoid chrome.storage because it's some kind of "dumb" :)
So please have a look at this code:
function clearItem(symbol) {
var remove = [];
chrome.storage.sync.get(function(Items) {
$.each(Items, function(index, value) {
if (index == "symbol") remove.push(index);
});
chrome.storage.sync.remove(remove, function(Items) {
chrome.storage.sync.get(function(Items) {
$.each(Items, function(index, value) {
console.log("removed: " + index);
});
});
});
});
};

Read nested json file in javascript using node js in simple Key-> Value Pair format [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
I have been working with complex,nested JSON file as given below:
Update:: Nested JSON file snippet (example)
{
"sample": {
"someitem": {
"thesearecool": [
{
"neat": "wow"
},
{
"neat": "tubular"
}
]
},
"coolcolors": [
{
"color":"red",
"hex": "ff0000"
},
{
"color":"blue",
"hex":"0000ff"
}
]
}
}
I want to traverse through each and every value in this JSON file.
I have tried many npm nodejs packages to make nested JSON into plain, readable JSON format.(NPM Packages-> flattenr, flat, etc.).
Kindly someone help me to resolve this issue. Please give some better solutions with examples.
Yeah, that's a nice problem of recursion.
So, the general idea is a function with a for-loop.
2 things can happen: either it's a value, then you print it. Or it's a object, then you put that object through the same function.
<div id="log"></div>
<script>
var data = {
"sample": {
"someitem": {
"thesearecool": [
{
"neat": "wow"
},
{
"neat": "tubular"
}
]
},
"coolcolors": [
{
"color":"red",
"hex": "ff0000"
},
{
"color":"blue",
"hex":"0000ff"
}
]
}
};
function readAllJson(data, level) {
var resultString = '';
for(var i in data) {
var type = typeof data[i];
switch(type) {
case 'object':
resultString += indent(level) + i +':<br/>'+ readAllJson(data[i], level + 1); // recursion
break;
default:
resultString += indent(level) + i +': '+ data[i] + '<br/>';
break;
}
}
return resultString;
}
function indent(level) {
var result = '';
for(var i=0; i<level; i++) {
result += ' '; // HTML space character
}
return result;
}
window.onload = function() {
var log = document.getElementById('log');
var result = readAllJson(data, 0);
log.innerHTML = result;
}
</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.

Edit javascript array without reloading the page

I have a literal array that is loaded when the page loads... See below:
<script type="text/javascript">
var members = [
{
name:"Alan Lim",
id:"54700f06-a199-102c-8976-b1732b7ffc74",
positions:[
{
id:"4cdeb2a2-8897-102d-80ee-95364de284f0"
}
]
},
{
name:"Ben Sinclair",
id:"ed34b5a4-9b2f-102c-8475-9e610b13400a",
conflict:"true",
positions:[
{
id:"f00c2128-8895-102d-80ee-95364de284f0"
},
{
id:"f00c68ea-8895-102d-80ee-95364de284f0"
},
{
id:"4cde6824-8897-102d-80ee-95364de284f0"
},
{
id:"4cde9ea2-8897-102d-80ee-95364de284f0"
}
],
locations:[
{
id:"88fb5f94-aaa6-102c-a4fa-1f05bca0eec6"
},
{
id:"930555b0-a251-102c-a245-1559817ce81a"
}
]
},
{
name:"Debbie Wright",
id:"fa49307a-9cfb-102d-bd08-842c500d506d"
}
]
</script>
Is there anyway to edit the array without reloading the page? For example, I want to add conflict:"true" to Alan Lim...
E.g:
Change this:
{
name:"Alan Lim",
id:"54700f06-a199-102c-8976-b1732b7ffc74",
positions:[
{
id:"4cdeb2a2-8897-102d-80ee-95364de284f0"
}
]
},
To this:
{
name:"Alan Lim",
id:"54700f06-a199-102c-8976-b1732b7ffc74",
conflict:"true",
positions:[
{
id:"4cdeb2a2-8897-102d-80ee-95364de284f0"
}
]
},
Trust that makes sense :) The reason for this is because I use other JavaScript to pull information from this array. When I make a change with the other JavaScript I want to add and subtract to this array to reflect the changes...
You can loop through to find the member you want (by name it seems given the question) then edit it, like this:
for(var i=0; i<members.length; i++) {
if(members[i].name == "Alan Lim")
members[i].conflict = "true";
}
You can give it a try here, or make it a bit more generic like this:
function setProp(name, prop, value) {
for(var i=0; i<members.length; i++) {
if(members[i].name == name)
members[i][prop] = value;
}
}
Since your array is numerically indexed, Can you not just do:
members[0]['conflict'] = "true";

Categories

Resources