error when using "push()" to add string to JSON array - javascript

I want to add strings to my JSON file which looks like this:
{
"items": []
}
which is required like this: var items = require("../../config/item.json");
Then I am writing it to the array like this: items["item"].push(str);,
which triggers an error: Cannot read property 'push' of undefined
How can I add the string "str" to the array?
After pushing it, i write it to the file like this:
let data = JSON.stringify(items);
fs.writeFileSync("../../config/item.json", data, (err) => {
if (err) {
throw err;
} else {
console.log("item written successfully.");
}
});
Thanks in advance.

You need to use the push() method on the array, your property selector ['item'] doesn't exist it's ['items']. The json file itself is not an array, it's an object.
To push in to the array:
var items = require("../../config/item.json");
items.items.push(str);
Or you can do items['items'].push(str) where ['items'] is a property selector.

Related

Vue js : Filter dynamic data

In my Vuejs below I want to filter the reviewed:true only questions, and get the length of them, but my code below gives an error TypeError: question.reviewed.includes is not a function ,is there a way to do it?
Here is the screenshot about the json file:
JSON File
filterReviewed() {
return this.questions.filter((question) => {
return (
question.reviewed
.includes('true')
);
});
},
includes is a method of Object of Array type. Directly judge attribute reviewed is OK
filterReviewed (){
return this.questions.filter((question) => question.reviewed);
}
To filter the reviews try this:
filterReviewed() {
return this.questions.filter((question) => question.reviewed === true);
},
To get the filterReviewed length try this:
filterReviewed.questions.length

Create new object and write to file with fs.writeFile()

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");
}
});

Access JSON Array with Javascript?

I get an JSON array via an Ajax request. This one looks like this:
{
"data":{
"title":"Frau",
"academic_title":null,
"first_name":"Lynda",
"last_name":"McCrow",
"company":"Tekfly",
"street":"Sage",
"zip":"4860-077",
"country":"Portugal",
"city":"Quinta",
"phone":"6727086107",
"fax":"4941912651",
"mobile":"3722716317",
"email":"lmccrow7#newyorker.com",
"web":"shop-pro.jp",
"mailbox":"81-0982335",
"mailbox_country":"Indonesia",
"mailbox_zip":null,
"mailbox_city":"Susoh",
"birthday":"1977-02-11"
}
}
But I have no idea, how to access the JSON array. I already tried all of this:
success: function(data) {
console.log(data[0].data.title);
console.log(data[0].title);
console.log(data.data[0].title);
console.log(data.title);
}
Can you guys give me a hint?
Kind regards
You have tried everything except:
data.data.title
It's an Object and you need to use Object.key() or something to iterate. Technically, it's like this:
// Inside your function, this is what gets passed.
data = {
"data":{
"title":"Frau",
"academic_title":null,
"first_name":"Lynda",
"last_name":"McCrow",
"company":"Tekfly",
"street":"Sage",
"zip":"4860-077",
"country":"Portugal",
"city":"Quinta",
"phone":"6727086107",
"fax":"4941912651",
"mobile":"3722716317",
"email":"lmccrow7#newyorker.com",
"web":"shop-pro.jp",
"mailbox":"81-0982335",
"mailbox_country":"Indonesia",
"mailbox_zip":null,
"mailbox_city":"Susoh",
"birthday":"1977-02-11"
}
};
for (var key in data.data) {
console.log(`${key}: ${data.data[key]}`);
}
data is not an array, nor JSON, it's an object literal. Your last try comes close, but you need to access
data.data.title
or you could destructure data in the success param
success: function({data}) {
// now you could access data.title directly
console.log(data.title);
}

Pulling Out Value from Within Two-Levels Deep Object

I am trying to retrieve one particular value from within a two-levels deep object data structure. First off, though, I am saving into a variable within the function, like this:
getTargetId() {
if (this.authenticationService.isAuthenticated()) {
const userInfo = sessionStorage.getItem('currentUser');
console.log(userInfo);
}
}
From:
console.log(userInfo);
I get this back in the console:
{"token":"sometoken.value","data":{"_id":"8cd0362c0", "phone":"555-4343"...}
What I want to do is specifically pull out the "_id" value here.
I tried:
console.log(userInfo.data._id);
But then my IDE is showing me an error:
'Property '_id' does not exist on type 'string'.
How do I dig out "_id" in this case?
You are accessing it wrong
Try userInfo.data._id
In the log of your object you can see by the {} notation that data is another object, so after accessing data you can access its properties just as you would with any other object.
I also see that you are getting
'Property '_id' does not exist on type 'string'.
This could mean that you never parsed the information. To find out if this is the case this should be right:
Running->
console.log(userInfo);
Returns->
{"token":"sometoken.value","data":{"_id":"8cd0362c0", "phone":"555-4343"...}
Just after this code:
Running->
console.log(typeof userInfo);
Returns->
"string"
With your edits, I can see that this is the case.
Try:
userInfo = JSON.parse(sessionStorage.getItem('currentUser') );
console.log(userInfo.data._id);
The _id property is under the data key:
const response = {
"token":"sometoken.value",
"data": {
"_id":"8cd0362c0",
"phone":"555-4343"
}
};
console.log(response.data._id)
You can also use destructuring:
const { _id } = response.data;
console.log(_id)
or:
const { data: { _id }} = response;
console.log(_id);
So, as #jonsharpe pointed out, the key was to JSON.parse the string first. So this gets me the value I need for "_id":
getTargetId() {
if (this.authenticationService.isAuthenticated()) {
const userInfo = JSON.parse(sessionStorage.getItem('currentUser'));
console.log(userInfo.data._id);
}
}
Actually your string is returned as JSON string. So you have to parse it into object using JSON.parse() if you are using js or with $.parseJSON() if you are using Jquery. So your updated code now looks like this.
var user ='{"token":"sometoken.value","data":{"_id":"8cd0362c0", "phone":"555-4343"}}';
var k = JSON.parse(user);
alert(k.data._id);
And Fiddle is here.
Thank You

Delete specific object from Parse.com

In my cloud code I want to retrieve the first object in the "Messages" class. Then i want to grab some information from that object, send it to another class, and finally delete that object from the "Messages" class i originally pulled it from. Below is my code, however it doesn't work. How should i rework this?
Should i use a different approach than the "destroy" method such as collection.remove?
Parse.Cloud.afterSave("sendMessage", function(Parse.Message, response) {
var body = null;
var senderName = null;
var senderId = null;
var randUsers = [];
var query = new.Parse.Query(Parse.Message);
query.find({
success: function(results){
body.push(results[1].get("messageBody"));
senderName.push(results[1].get("senderName"));
senderId.push(results[1].get("senderId"));
results[1].destroy({
success: function(results[1]){
//the first object in the class "Messages" was deleted
}, error: function(results[1], error){
//the first object was not deleted
}
});
response.success(getUsers);
}, error: funtion(error){
response.error("Error");
}
});
});
to avoid confusion: "getUsers" is an arbitrary function call.
Duplicate question with the entry;
Query entire class vs first object in the class
However, if you want to delete a specific object you need something which uniquely identify the
object. Then, one way is using the Parse object id to delete the object from class.
To delete the object via cloud, you need to use the destroy method of ParseObject. But if you have multiple objects then you can use destroyAll method. One example of ParseObject delete method on javascript API is below;
var yourClass = Parse.Object.extend("YourClass");
var query = new Parse.Query(yourClass);
query.get("yourObjectId", {
success: function(yourObj) {
// The object was retrieved successfully.
yourObj.destroy({});
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and description.
}
});
Hope this helps,
Regards.
Some changes into above :
var missingDataQuery = new Parse.Query(missingDataObj)
missingDataQuery.equalTo('projectId',project);
var getMissingData = missingDataQuery.find({
success: function(yourObj) {
console.log('here')
yourObj[0].destroy({})
},
error: function(object, error) {
}
});
Here we getting object and then destroying it.
func deleteImage(imageId: String) {
let query = PFQuery(className: "ClassName")
query.whereKey("imageId", equalTo: "\(imageId)")
query.findObjectsInBackground {
(objects:[PFObject]?, error: Error?) -> Void in
if error == nil && (objects != nil) {
for object in objects! {
object.deleteInBackground()
print("object deleted")
}
}
}
}

Categories

Resources