Is it possible to send non-editable arrays?
What i'm trying to send is:
var items = [];
//console.log(JSON.stringify(items));
allitems = JSON.stringify(items);
[{
"assetid": "7814010469",
"classid": "1797256701",
"instanceid": "0",
"name_color": "D2D2D2",
"icon_url": "-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXU5A1PIYQNqhpOSV-fRPasw8rsUFJ5KBFZv668FFYznarJJjkQ6ovjw4SPlfP3auqEl2oBuJB1j--WoY322QziqkdpZGr3IteLMlhpw4RJCv8",
"market_hash_name": "Gamma Case"
}]
$.ajax({
type: "POST",
async: true,
url: "jackpot/deposit",
data: {
myData: allitems
},
success: function(body) {
toastr["info"]("Success! Our bots are generating your trade. Please wait...", "Inventory");
},
});
But I want to make it not editable via the console.
And send it.
You should be able to use Object.freeze() to prevent the array from being changed. For example:
var arr = [1, 2, 3];
Object.freeze(arr);
arr.push(4); // error
Related
If I have the below json data for example, how would I compare this array to return true based on a single element of the array?
In this example, Id like true to be returned as the url's are all the same, ignoring all other objects. However if one of the url's were different false should be returned.
[
{
id: 1,
name: "a",
url: "http://www.google.co.uk"
},
{
id: 2,
name: "b",
url: "http://www.google.co.uk"
},
{
id: 3,
name: "c",
url: "http://www.google.co.uk"
}
]
I have tried to use a filter to take only the url object and then compare that, however that hasn't worked.
Thanks for any suggestions
I think you could use the "every" method to check that.
You could get the url of the first position and check with that if the whole array satisfy your condition.
const firstUrl = yourArray[0].url;
const allUrlsAreTheSame = yourArray.every(item => item.url === firstUrl);
It's not nearly as elegant as the .every() approach, but it's good to show different ways of approaching array iterations
const data = [{
id: 1,
name: "a",
url: "http://www.google.co.uk"
},
{
id: 2,
name: "b",
url: "http://www.google.co.uk"
},
{
id: 3,
name: "c",
url: "http://www.google.co.uk"
}
]
function urlsAreIdentical(arr) {
let theurl, urlsAreTheSame = true;
arr.forEach(obj => {
if (!theurl) theurl = obj.url;
else if (theurl != obj.url) urlsAreTheSame = false;
})
return urlsAreTheSame;
}
console.log(urlsAreIdentical(data));
data.push({
id: 4,
name: "c",
url: "http://www.yahoo.co.uk"
});
console.log(urlsAreIdentical(data));
I have a Json response, it looks like this:
[{
"item": "1",
"addr": "someaddr"
},
{
"item": "2",
"addr": "someotheraddr"
}
]
How can i loop through this record and print, let's say, the addr field of each one?
I tried the following:
$.ajax({
url: "someurl",
type: 'get'
success: function (data) {
$.each(data, function(key, val) {
console.log(key, val)
});
alert("Success");
}
});
But it throws the following error: TypeError: Cannot use 'in' operator to search for 'length'
I'm sure it's because i'm not properly looping throught the Json Data. Can someone point me out where i'm breaking the loop?
Edit: the Json response is retrieved from an API endpoint using Jquery.
You need to use dataType: 'json' to tell jQuery to parse the response as JSON (if the server doesn't send Content-type: application/json).
$.ajax({
url: "someurl",
type: 'get',
dataType: 'json',
success: function (data) {
$.each(data, function(key, val) {
console.log(key, val.addr)
});
alert("Success");
}
});
The problem may be that you're not passing back a JSON object, you're passing back individual lines of JSON. So if you have control over your JSON response, you should make the json look like this:
[
{"item": 1, "addr": "someaddr"},
{"item": 2, "addr": "someotheraddr"}
]
(note that it is wrapped in an array, has commas between each line, and has double quotes around the strings).
Then you can use your each function. I have included a snippet below that you can try it out with.
var data = [
{"item": 1, "addr": "someaddr"},
{"item": 2, "addr": "someotheraddr"}
];
$.each(data, function(key, val) {
console.log(val.addr)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
I am translating some code from python into Javascript (I am inexperienced in JS), as part of it I need to write a JSON, currently when writing in JS it looks like this(just a brief sample):
[
{
"Num": "000000",
"Status": 1,
},
{
"Num": "00001",
"Status": 0,
},
]
However I need it to look like this:
{
"mydata": [
{
"Num": "00000",
"Status": 1,
},
{
"Num": "00001",
"Status": 0,
},
]
}
How can I adapt my code to generate this single main key for the whole JSON, here is what I have so far:
var jsondata = []
for (result in results) {
jsondata.push({
'Num' : idnum,
'Status': results[result].StatusID,
})
}
let data = JSON.stringify(jsondata, null, 2)
fs.writeFileSync('testingjson.json', data)
This code here sits in a for loop, so I cannot just write the key in the push, it would generate the mydata key for every iteration of the loop.
I need to know how I can pre-define the mydata, has anyone got a good method to do this?
Just define mydata as an array, and then at the end, create an object where mydata is one of the keys:
const mydata = []
for (const result in results) {
mydata.push({
'Num' : idnum,
'Status': results[result].StatusID,
});
}
const json = JSON.stringify({ mydata }, null, 2);
If you want to use a different key name, then change it when stringifying, eg:
const json = JSON.stringify({ someKeyName: mydata }, null, 2);
If results is an object, then you can make the code more concise with Object.values and map:
const Num = idnum;
const mydata = Object.values(results)
.map((item => ({ Num, Status: item.StatusID }));
const json = JSON.stringify({ mydata }, null, 2);
fs.writeFileSync('testingjson.json', data)
I'm a real noob when it comes to JSON. Any help on the following would be fantastic.
console.log(obj.id); in the code below returns nothing in the console - I need to understand why? I expect it two log two things in the console based on the JSON data.
JS:
var matchTeamAStatsJSON
$.ajax({
type: 'GET',
url: 'http://www.website.com/apipathblahblahblah',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
matchTeamAStatsJSON = data;
console.log(matchTeamAStatsJSON);
for(var i = 0; i < matchTeamAStatsJSON.length; i++) {
var obj = matchTeamAStatsJSON[i];
console.log(obj.id);
}
}
})
JSON:
{
"records": [
{
"id": "recGWUWqwjUNLpekA",
"fields": {
"playerSprints": 12,
"playerDistanceCovered_km": 6.23
},
"createdTime": "2018-03-22T18:16:56.000Z"
},
{
"id": "recx5pMFpxnRwR4La",
"fields": {
"playerSprints": 12,
"playerDistanceCovered_km": 6.23
},
"createdTime": "2018-03-19T11:35:11.000Z"
}
]
}
You could use Array.prototype.forEach() and do:
const data = {"records": [{"id": "recGWUWqwjUNLpekA","fields": {"playerSprints": 12,"playerDistanceCovered_km": 6.23},"createdTime": "2018-03-22T18:16:56.000Z"},{"id": "recx5pMFpxnRwR4La","fields": {"playerSprints": 12,"playerDistanceCovered_km": 6.23},"createdTime": "2018-03-19T11:35:11.000Z"}]};
data.records.forEach(obj => console.log(obj.id));
If the JSON example you posted below is the response from the GET request, data is equal to "records" which doesn't have an and "id" property. However, each instance of the array it contains does.
You need to get inside that array first and then get the "id" property of each element: console.log(obj.records[i].id) should get you want.
Hope this helps!
Hello i have problem to load data in flotchart.js
here's the original code that works
var pageviews = [
[1,2],
[2, 3]
];
var visitors = [
[1, 3],
[2, 2]
];
var plot = $.plot($("#site_statistics"), [{
data: pageviews,
label: "Unique Visits"
}, {
data: visitors,
label: "Page Views"
}]);
but when i change the data that i load from json it doesn't work.
here's the data json on load_statistik_bidang.php:
[{"data":[["1",12],["1",11],["3",10],["14",9]],"label":"EMSA"},{"data":[["1",12],["4",9]],"label":"BSSA"},{"data":[["1",2],["1",10]],"label":"OSSAC"}]
if i copy the json in manual it's works but when im using function to load the data it doesnt work .
code that i load the json is like this :
function loadMyData(){
$.ajax({
url:"load_statistik_bidang.php",
dataType: "json",
method:"get",
success: function(data){
tampung = data;
console.log(data.EMSA);
}
});
}
var plot = $.plot($("#site_statistics"), tampung);
any ideas for this? thanks
Your JSON is broken/invalid. You're not closing your first data array.
Should look like this:
[{
"label": "EMSA",
"data": [
[
"1",
12
],
[
"1",
11
]
] // <-- you forgot this
},
{
"label": "BSSA",
"data": [
[
"1",
12
],
[
"4",
9
]
]
}
]
You can use this site to validate it in the future:
http://jsonlint.com/