I have a realm Organization and Ticket. An organization has many tickets. So to update organization, it looks like this:
try {
realm.write(() => {
realm.create('Organization', {
id: organization.id,
name: organization.name,
ticket: downloadTickets(organization.id)
}
, true)
})
console.log("inserting/updating ogranization")
} catch(err) {
console.warn(err)
}
The downloadTickets function returns an array of objects. This will work on my initial write. But if I want to update the array, I want to add objects to the array but not overwrite the whole array. How can I do this without getting the current values, appending it to the new ones, and returning it to the object? That seems too slow.
When you use create() with the true parameter you are overwriting the properties of the existing object. What you want is to modify the existing data.
To do this you'll have to reference the original array in some fashion. You can either iterate over the new Tickets and push() them into the array, or use concat() on the existing array and passing in the new array.
try {
realm.write(() => {
var org = realm.create('Organization', {
id: organization.id,
name: organization.name
}
, true)
// Do this
var newTickets = downloadTickets(organization.id);
for(var i = 0; i < newTickets.length; i++) {
org.ticket.push(newTickets[i]);
}
// or this
org.ticket = org.ticket.concat(downloadTickets(organization.id));
})
console.log("inserting/updating ogranization")
} catch(err) {
console.warn(err)
}
As a side note: Referencing the array does not load the whole thing into memory. The actual data of the array is only on disk until you explicitly accesses it, Realm then reads it from disk. Accessing the array to add the new Tickets is not an expensive operation.
Related
I have a function that takes a string from a search field during runtime, and stores it to localstorage. Since we want to store all search strings from the end user to record it, we need to get the current data from localstorage, and add the latest search string.
Here is my code:
const setDatatoLocalStorag = (searchQuery: string) => {
let searchHistory = localStorage.getItem("searchHistory");
let searchQueryArr = [];
if (searchHistory) {
JSON.parse(searchHistory);
searchQueryArr.push(searchQuery, searchHistory);
} else {
searchQueryArr.push(searchQuery);
}
localStorage.setItem("searchHistory", JSON.stringify(searchQueryArr));
}
Lets assume we run the function twice, with the searchQuery "dog" and "cat". This is how it will look like in localstorage:
["cat","[\"dog\"]"]
I believe localstorage will get the item as string "[myData]" which will cause the error. How to properly handle this?
I have tried to follow How to store an array of objects in Local Storage? withous success.
The problem is you aren't assigning JSON.parse(searchHistory); to a variable. I think what you want to do is this:
var searchQueryArr = ['dog'];
localStorage.setItem("searchHistory", JSON.stringify(searchQueryArr));
var searchHistory = JSON.parse(localStorage.getItem("searchHistory") || '[]');
console.log(searchQueryArr, searchHistory);
Note I wasn't able to get this to work with the inline editor, but I did try it on a real server and it worked.
Make a setter/getter pair that hide the encoding/unencoding. Then add a higher-level push that does a get and a set...
// const pretend local storage, keys => strings
const myLocalStorage = {}
function mySetItem(key, value) {
// use the actual local storage setItem() here
myLocalStorage[key] = JSON.stringify(value);
}
function myGetItem(key) {
// use the actual local storage getItem() here
return JSON.parse(myLocalStorage[key]);
}
function myPush(key, value) {
let current = myGetItem(key);
current.push(value)
mySetItem(key, current)
}
// test
const key = 'myKey'
mySetItem(key, []);
myPush(key, { message: 'hello' })
myPush(key, { message: 'dolly' })
console.log(myGetItem(key))
I want to rename the factORLossTree into savefactORLossTree dynamically inside the function from below payload.
I am getting below data on payload after submitting the form.
{
"cluster":"Europe",
"factory":"Caivano",
"factoryId":"Caivano",
"factORLossTree":[
{
"skuid":"000000000067334539",
"skuDescription":"MAG 55ml Mini PistHazelnut 8MP x6x120 EB",
"levelLosses":[
{
"level1":"Line Scheduling Losses",
"variancePer":100
}
],
"isRowChecked":false
}
],
"submitType":"po"
}
Below is my code .
saveOrUpdateORData() {
const formData = Object.assign({}, this.orLosstreeForm.value);
if (formData.factORLossTree.length === 0) {
this.dialogService.openDialog('Data Not Available');
return false;
}
console.log(formData,"formdata");
return;
}
Expected Output
{
"cluster":"Europe",
"factory":"Caivano",
"factoryId":"Caivano",
"savefactORLossTree":[
{
"skuid":"000000000067334539",
"skuDescription":"MAG 55ml Mini PistHazelnut 8MP x6x120 EB",
"levelLosses":[
{
"level1":"Line Scheduling Losses",
"variancePer":100
}
],
"isRowChecked":false
}
],
"submitType":"po"
}
Can anyone please help me to do this.
Sure thing! Worth mentioning that this issue is purely JS and has nothing to do with your framework (e.g. - Angular)
To the point: let's assume that your payload is stored in a variable called payload
First - check if the property exists. Then - replace it:
const propertyName = 'put the property name here'
const newPropertyName = 'put the new property name here'
if (payload.hasOwnProperty(propertyName)) {
payload[newPropertyName] = payload[propertyName]
delete payload[propertyName]
}
Why this is working? Because we are creating another reference to the original data before deleting the property. At the end we end-up with one reference having the updated name
If (from some reason) you need to clone the data, follow this pattern instead:
if (payload.hasOwnProperty(propertyName)) {
const clone = JSON.parse(JSON.stringify(payload[propertyName]))
payload[newPropertyName] = clone
delete payload[propertyName]
}
I assume that your property always contains an object. If the type of the property is primitive (e.g. - number, string or boolean) you can just skip the cloning phase all together (primitives are copied by their values while only objects are handled by their reference)
I am trying to update a mongoose document, But its a deeply nested array of objects and I am having trouble updating it using the spread operator. I have an array of image-links and I wanna iterate through the relationships array in the database and add an image to each relation. The code shows my approach, but the syntax is wrong. I have added a db image which shows where I wanna add the image variable.
// Get Images
const imagesData = await axios.get(
"https://randomuser.me/api/?results=4&gender=male"
);
const images = [];
imagesData.data.results.forEach((result) => {
images.push(result.picture.large);
});
// Update Company
for (let i = 0; i <= 3; i++) {
const updateCompany = await Companies.findByIdAndUpdate(
req.params.id,
{ relationships: [
...relationships,
relationships[i]: {
...relationships[i],
image: images[i]}
] },
{ new: true }
).exec();
}
Also I am using a mongoose query inside a for loop. Is it the right way to do it.
mognoDB
You should fetch the document that you want. Then treat the fetched object as a javascript object and add or update whatever you want then use .save() function provided by mongoose.
let result = await Companies.findById(id);
result = result.map((company)=>{
update your object here
})
result.save()
The .save() function will take care of updating the object in the database
I have a vue object with all these getters and setters, here is a screenshot from the console.log:
The structure of the actual DATA (the not-vue stuff) looks like this:
{
Internal_key: "TESTKEY_1",
extensiontable_itc: {
description_itc: "EXTENSION_ITC_1_1",
description_itc2: "EXTENSION_ITC_1_2",
},
extensiontable_sysops: {
description_sysops: "EXTENSION_SYSOPS_1"
}
}
The data might look different in other usecases.
There might be more or less key-value pairs on the outer object, and the keys might be named differently as well. Same goes for the nested objects and their contents.
Is there some convenient way to extract this data into a plain JS Object?
If not, how can I best loop the vue object to extract the data "manually"?
The AJAX request shall be performed by an axios request, if this is important as well.
EDIT:
Here is the relevant data in vue:
data() {
return {
editingRecord: {
original: null,
copy: null
}
}
}
During my programflow, both editingRecord.orginal and editingRecord.copy receive data from an inputform. copy sets its data to original if the user clicks the save/send button. Then, I want to take the data from editingRecord.original with both its keys and values and send them to the server via AJAX request.
Its best not to mix jQuery with Vue so here's how you would do it using Axios https://github.com/axios/axios
methods: {
submit() {
const body = this.editingRecord.original
// make changes to body
axios.post( "backend_url", body )
.then(function(resp){
console.log(resp)
});
}
}
Okay, I found the solution.
let vueObject = Object.entries(this.editingRecord.original)
for(const[key, value] of vueObject){
if(typeof value == 'object' && value !== null){
for(const [nestedKey, nestedValue] of Object.entries(value)){
result[nestedKey] = nestedValue
}
}else{
result[key] = value
}
}
console.log("resultObject is", result)
This way you can iterate over all properties including the properties of nested objects and reassign both key and value to a fresh, one-dimensional array.
There are two things I want to do:
I want to create a new array of objects from an existing object,
And increment the object so each object can have a count id of 1,2,3 etc
My issue is that when I write to the file it writes only 1 random object to the file and the rest don't show. There are so errors and all the objects have the same increment value. Please explain what I am doing wrong. Thanks.
Code:
data.json:
{
"users":[
{
"name":"mike",
"category":[
{
"title":"cook",
}
],
"store":{
"location":"uptown",
"city":"ulis"
},
"account":{
"type":"regular",
"payment":[
"active":false
]
}
}
]
}
index.js:
const appData = ('./data.json')
const fs = require('fs');
let newObject = {}
appData.forEach(function(items){
let x = items
let numincrement = 1++
newObject.name = x.name
newObject.count = numincrement
newObject.categories = x.categories
newObject.store = x.store
newObject.account = x.account
fs.writeFile('./temp.json', JSON.stringify(newObject, null, 2),'utf8' , function(err, data) {
// console.log(data)
if(err) {
console.log(err)
return
} else{
console.log('created')
}
})
})
There are a whole bunch of problems here:
You're just rewriting the same object over and over to the file. fs.writeFile() rewrites the entire file. It does not append to the file. In addition, you cannot append to the JSON format either. So, this code will only every write one object to the file.
To append new JSON data to what's in the existing file, you would have to read in the existing JSON, parse it to convert it to a Javascript array, then add new items onto the array, then convert back to JSON and write out the file again. For more efficient appending, you would need a different data format (perhaps comma delimited lines).
Your loop has all sorts of problems. You're assigning to the same newObject over and over again.
Your numincrement is inside the loop so it will have the same value on every invocation of the loop. You can also just use the index parameter passed to the forEach() callback instead of using your own variable.
If what you're trying to iterate over is the users array in your data, then you may need to be iterating over appData.users, not just appData.
If you really just want to append data to a text file, the JSON is not the easiest format to use. It might be easier to just use comma delimited lines. Then, you can just append new lines to the file. Can't really do that with JSON.
If you're willing to just overwrite the file with the current data, you can do this:
const appData = ('./data.json').users;
const fs = require('fs');
// create an array of custom objects
let newData = appData.map((item, index) => {
return {
name: item.name,
count: index + 1,
categories: item.categoies,
store: item.store,
account: item.account
};
});
// write out that data to a file as JSON (overwriting existing file)
fs.writeFile('./temp.json', JSON.stringify(newData, null, 2),'utf8' , function(err, data) {
if (err) {
console.log(err);
} else {
console.log("data written");
}
});