How should i attach jsons to variable/another json in javascript - javascript

It should be answer here but I can't find.
I have script like this:
for (count=1;count<5;count++) {
obj[count]=json[count]
}
Then I want connect this. But I made it manually:
objs=[...obj[1].posts,...obj[2].posts,...obj[3].posts,...obj[4].posts]
How I can automatically connect all this. Like this:
for (count=1;count<5;count++) {
obj[count]=json[count]
objs+=[...obj[count].posts]
}
Example:
var obj=[];
var objs=[];
obj[1]=[123]
obj[2]=[456];
obj[3]=[789];
Should get:
objs=[...obj[1],...obj[2]...obj[3]]
alert(objs)
Will result: 123,456,789

By using : filter & map
var obj=[];
var objs=[];
obj[1]=[123]
obj[2]=[456];
obj[3]=[789];
objs = obj.filter(Boolean).map(a=>a[0])

Sorry because I am dumb. I used objs,push(obj) with loop. Now I don't need loop of creating value. It now work well.
Script that I use now if you need:
obj=[]
for (count=1;count<5;count++) {
//Your script that gets json
...
//If your json is string (i don't know is every json in internet is string)
json=JSON.parse(json string that you get
obj.push(...json.posts) //You can change "posts" with array/object (I dont know what is this) that you want or without it if json is clean array
}

Related

Parse JSON data, and then pass all its values to another function

I'm building this website: http://collections.design
The way it works is by reading all tools data from a JSON, using jQuery (I don't know much javascript). Then, you can click on an item and a side panels opens with further information. But there's a lot of repeated code, so I'm trying to optimise it a bit.
First I parse the JSON:
// The data source
var data_source = "../data/tools/tools.json";
// Parsing the JSON
$.getJSON(data_source, function(data) {
$.each(data, function(key,val) {
// And I'm storing all of its values in variables, to make them easier to read:
var name = val.availability.name;
var linux = val.os.linux;
// Then I'm using all that to render each item on screen
…
});
});
Each of the items has a button that calls another function to create and open the side panel. The side panel reuses that item's data from the JSON. This function to create the side panel is using the name variable as parameter, but then inside is parsing the JSON again to get the rest of the values it needs.
My question is:
How can I "encapsulate" all variables when I do the JSON parsing, then pass it as a parameter to the other function; and finally, individually read each of those values in the other function?
I tried working with arrays. But didn't manage it to work, also keeping in mind that I'm trying to simplify things, not repeat myself, and keep short names…
Maybe I'm asking too much, but any pointers or links to doc will be appreciated.
I see two ways of doing this.
1) Save the JSON data outside the scope so you can reuse it and pass the index of the data you want.
Something like this
// The data source
var data_source = "../data/tools/tools.json";
var all_data;
// Parsing the JSON
$.getJSON(data_source, function(data) {
all_data = data;
$.each(data, function(key,val) {
$('.button').on('click', function() { callToOtherFunction(key) })
});
});
function callToOtherFunction(key) {
console.log(all_data[key]);
}
2) As Sam Axe said, pass the data directly to the function
// The data source
var data_source = "../data/tools/tools.json";
// Parsing the JSON
$.getJSON(data_source, function(data) {
$.each(data, function(key,val) {
$('.button').on('click', function() { callToOtherFunction(key) })
});
});
function callToOtherFunction(val) {
console.log(val);
}
Here's a working fiddle.
The data is already "encapsulated" in the data object. Pass that object to the function that you want to use the data in.
You could always construct a new object - but what's the point - it's already in the data object.

How to save strings to SPECIFIC location in p5.js

Here I have a code that I was playing around with.
It loads a string within my file and saves an unimportant one.
var file = "1";
var result;
var meString;
var splitMeString;
function preload() {
result = loadStrings("assets/save/"+file+".txt");
}
function setup() {
createCanvas(1000,650);
}
function draw() {
meString = result+'';
splitMeString = splitTokens(meString, ',');
text(meString,20,20);
console.log(splitMeString[2]);
}
function mousePressed(){
saveStrings("happy");
}
but how would I save a string to a specific location? Say I wanted to overwrite the file ("file")?
Questions like these are best answered by looking in the reference.
According to the reference, the saveStrings() function can take three arguments:
Syntax
saveStrings(list,filename,[extension])
Parameters
list String[]: string array to be written
filename String: filename for output
extension String: the filename's extension
So it sounds like you're looking for something like this:
saveStrings(yourArray, "file", "txt");
Also note that the third argument is optional, so this should also work:
saveStrings(yourArray, "file");
If you use the functions storeItem() and getItem() you can save strings to your program, this won't save it to a specific file embedded in your code but it will save it to your code. You can call whatever you stored in storeItem() with getItem()even after you close out of the tab. If you need any more info on it you can find it on the reference page here.
Hope this helps!

How to use .$watch to get the updated json array length from firebase

I have a code that get json array data from firebase...
var ref = new Firebase("firebase object path");
var sync = $firebase(ref);
$firebaseArray(ref).$loaded().then(function(data){
console.log(data.length)//here i get the length
});
From the above code i get the array length but when o delete a value from the firebase database the length is not updated... but to do that i dont know how to use .$watch ... can anyone help me how to integerate .$watch in the above code?
It is not necessary to use $watch. He will be greatly slow down Your website. Use the construction with "on":
ref.on('child_added', function(data){
console.log(ref.length);
});
ref.on('child_changed', function(data){
console.log(ref.length);
});
Try something like this (I have not tested this)

How to create an array and store in local storage using json

Hi guys so i have a form which takes in data like item name, code etc, so when i press the enter button...iv used json stringify and get an alert of what is stored in the local storage. However when i click reset and create a new item it just shows the new item, is there anyway i could store all my items created in local storage...? this is part of my coding. Im a beginner so please excuse if the question is too simple
Thanks
$('#myBox #EnterButton').click(function() {
ItemData = {
'ItemCode' : $('#ItemCode').val(),
'ItemName' : $('#ItemName').val()
};
localStorage.ItemData=JSON.stringify(ItemData);
$('#myBox').slideUp();
});
...
$('#myBox2 #EnterButton').click(function() {
if (localStorage.ItemData) {
alert(localStorage.ItemData);
ItemData = JSON.parse(localStorage.ItemData);
}
if (ItemData.ItemCode) {
$('#myBox #ItemCode').val(ItemData.ItemCode);
}
if (ItemData.ItemName) {
$('#myBox #ItemName').val(ItemData.ItemName);
}
})
and i have declared itemdata as a public variable. Hope its clear. TIA
You have to organize the way ÿou are using localStorage (a getter/setter class might help with maintenance). From your code above, it seems you are always overriding localStorage.ItemData with the values just inserted.
The solution would be for localStorage.Items to be an array and whenever you insert in that array, iterate over it to see if it's not already added (based on itemCode for instance) and override or insert a new item.
I presume this is enough for playing around. A more advanced concept than localStorage and used for slightly different purpuses would be pouchdb - websql in the browser.
Sounds like if you want multiple items to be stored, you should be using an array of itemData objects. You'll then have to parse this (array), and use something like Array.push(newItem) then stringify it again before saving it.
var allItems = localStorage.getItem('ItemData');
if(allItems == null) {
localStorage.setItem('ItemData', JSON.stringify([ItemData]));
} else {
allItems = JSON.parse(allItems);
allItems.push(ItemData);
localStorage.setItem('ItemData', JSON.stringify(allItems));
}

Filter json data in controller, the right way

(there are other questions but neither helped me out)
Hi, I would like to know if this is the right way to filter the results I get from service where I'm displaying only one result (like a detail).
I know I could use ng-repeat and filter it in the view and that is the cleanest, but I want to have more control over because I will re-use some of the data in the controller for other operations.
Right now I'm doing this:
$scope.savedEvents = Event.getPayedEvents(); //gets a list from service
//Goes through entire list and checks for a match
angular.forEach($scope.savedEvents, function(event) {
if (event.IdEvent == $stateParams.eventId) {
$scope.showEvent = event;
}
});
//now if there is a match I can use $scope.showEvent.eventName etc
Not sure if this would be easier using $filter to return just one event that has correct IdEvent. Or if someone has better solution, please let me know.
thanks
I don't see any problems with what you have, but you could inject the $filter service and do this one liner:
$scope.showEvent = $filter('filter')($scope.savedEvents, { IdEvent: $stateParams.eventId });
EDIT: Here is an easy way to resolve the result to a single value from the returned array:
var showEvents = $filter('filter')($scope.savedEvents, { IdEvent: $stateParams.eventId });
$scope.showEvent = showEvents && showEvents.length ? showEvents[0] : null;
In CoffeeScript it is a little more concise:
$scope.showEvent = $filter('filter')($scope.savedEvents, { IdEvent: $stateParams.eventId })?[0]

Categories