getting data from an object's array with vue.js - arrays

I am trying to access the following data in Vue.js
{"id":1,"name":"Westbrook","created_at":"2017-06-10T16:03:07.336Z","updated_at":"2017-06-10T16:03:07.336Z","stats":[{"id":1,"player_id":1,"points":2558,"assists":840,"rebounds":864,"created_at":"2017-06-10T16:03:07.373Z","updated_at":"2017-06-10T16:03:07.373Z"}]}
self.player = response.name works. now i need self.point
methods: {
fetchData: function() {
var self = this;
$.get("api/v1/players/1", function(response) {
console.log(response);
self.player = response.name;
self.point = response.stats.points
});
}
}
I have thus far tried response.stats["points"], response.stats[2], response.stats[ { points } ], response.stats[points]

The stats property in your json holds an array in which the first object has a property named points
So use response.stats[0].points
Keep in mind though that the stats is probably an array for a reason. It might hold more than one objects in the future, so always using the first element [0] might not be a valid approach.

I think it can help you
var json = JSON.parse(data);
json.stats[0].points

response = {"id":1,"name":"Westbrook","created_at":"2017-06-10T16:03:07.336Z","updated_at":"2017-06-10T16:03:07.336Z","stats":[{"id":1,"player_id":1,"points":2558,"assists":840,"rebounds":864,"created_at":"2017-06-10T16:03:07.373Z","updated_at":"2017-06-10T16:03:07.373Z"}]}
If you want to access the name
console.log(response.name) // Westbrook
If you want to access the stats data which contain list, simply target
let stats=response.stats[0] //By getting the first index in the list
Get the points in stats
console.log(stats.points) // 2588

Related

Mongoose querying the array... changing the elements of the array

I am trying to remove all the elements from the array in the MongoDB database, then I insert all the new array elements.
My Model is:
const mongoose = require('mongoose');
var schema = new mongoose.Schema({
email : {
type : String
},
password : {
type : String
},
stocks : {
type : [String]
}
}, {versionKey:false}, {_id: false});
module.exports = final = mongoose.model('users', schema);
My stocks array will then have some values. I am trying to remove those values using the following command:
I read at somewhere in Stack Overflow that to empty your array you can do many things but a set is the fastest way to do this. Please let me know if you know any other way which is better than this.
final
.findOneAndUpdate({email:"abcd#gmail.com"}, {$set:{stocks:[]}})
.then(()=>console.log("Data removed."))
.catch(err=>console.log(err));
Once data is removed it means the array will get emptied. Then I assign the whole set of the new array from my local variable like this:
const newData = {
stocks : ["abcd", "wxyz"]
};
Now I am trying to assign this new array to my database using this command:
final
.findOneAndUpdate({email:"abcd#gmail.com"}, {$set:{stocks:newData.stocks}});
It is emptying the array successfully, but when I am assigning new array it is not working and shows an empty array. Can anyone assist me with this, please?
Try with
final.findOneAndUpdate({email:"abcd#gmail.com"}, {$set:{stocks:newData.stocks}}, {new: true})
.then((doc)=>console.log(doc))
.catch(err=>console.log(err));
If you don't use a callback the query is not executed.
The query executes if callback is passed else a Query object is returned.
Mongoose documentation

Mongoose Model, cleaning/parsing an Array efficiently

I am having some issues with a mongoose array, it's likely due to my lacking understanding of the library, and I can't find the exact answer I'm looking for in the docs.
For starters I have my schema and model declarations:
const gConfig = new Schema({ aList: Array, maxChanLimit: Number }), globalConfiguration = mongoose.model('globalConfig', gConfig);
And I have my command which fetches the array, parses out _id, then pushes the new item to the array, and overwrites the existing one in the database.
if((message.author.id === g.ownerID) && (g.id.toString() === tocGuild) && message.content.startsWith("!updatealist"))
{
let mc = message.content.replace("!updatealist ", "");
globalConfiguration.findOneAndUpdate({},{$push: {"aList":mc }}, { upsert: true }, function(err, data) {
if (err) return console.log(err);
var str = JSON.stringify(data); str = str.replace(RegExp(/"_id"|"__v"|'/g),""); var arr = str.split(`","`);
});
}
I feel like there has to be a better way to do this, I've tried something like this based on what I've read:
globalConfiguration.findOneAndUpdate({},{$push: {"-_id aList":mc }}
However this did not remove _id from the array. I suppose how I'm doing it is a way to do it, but I know it isn't efficient, and isn't dynamic at all, it's also extremely bulky in terms of code and could be streamlined using the library.
In practice, what is the best way to properly read an array from a model with Mongoose? How do you read from the array without the additional objects Mongoose adds by default? What is the best way to add an item to an existing model?
Any help is appreciated, thank you.
if you want to have more control over the updating process, you can do it like this, in the mongoose documents it suggest you can first query the item/document you want to update, once that document is queried and there, you can make changes to it such as if it contains an array , you can push to it or pop from it or what ever..
its in your control
so,
if((message.author.id === g.ownerID) && (g.id.toString() === tocGuild) && message.content.startsWith("!updatealist"))
{
let mc = message.content.replace("!updatealist ", "");
globalConfiguration.findOne({"your query"}, function(err, data) {
if (err) throw (err);
data.array.push("something");
data.save();// save it again with updates
var str = JSON.stringify(data); str = str.replace(RegExp(/"_id"|"__v"|'/g),""); var arr = str.split(`","`);
});
}

Can't add objects in array Angular

I have Java service which retrieves table from oracle database and I want to display the result in Angular application, also I have an array of Objects in Angular:
resultSet:Info[]=[];
service:
pastHourInfo() {
const url='/SearchApp-1.0/users/transaction';
return this.http.get(url).pipe(map((data:any)=>data));
}
this is my service subscribtion:
checkPasHourInfo() {
this.searchService.pastHourInfo().subscribe(data => {
console.log("we got: ",data);
this.resultSet.push(data);
console.log(this.resultSet.length);
},
error => {
console.log("Error",error);
},);
Problem is the next. The result is 77 rows .
console.log("we got: ",data) gives correct result. you cans see it here
but console.log(this.resultSet.length); prints "1" when it must be 77.
What is the problem?
From your screenshot it seems that your are pushing the array into your result array, you could spread your data into the array as such:
this.resultSet.push(...data);
You are pushing an array into an array. So your array looks like this
resultSet[].length = 1;
resultSet[0].length = 77;
Instead of doing:
this.resultSet.push(data);
try this:
this.resultSet.concat(data);
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat
You can add array into another array as below:
this.resultSet.concat(data)

array push of records obtained from mongo db

In MEAN stack, I am trying to store the records obtained from mongo db in an array, but I am not able to store the record in an array.
This is my code, I am trying to push the records obtained from projectimage to fulldetails[] array, but it failed. Suggest me the possible solution to store the mongo db records to array
var express = require("express"),
router = express.Router(),
project = require("../../models/project.js"),
projectimage = require("../../models/projectimages.js"),
var details=data;
var fulldetails=[];
for (var i = 0; i < details.length; i++) {
var prjct_id=details[i]._id;
console.log('below'+i);
fulldetails.push(details[i]);
projectimage.findOne({projectId: prjct_id}, function(err, data){
fulldetails.concat(data);
});
console.log(fulldetails);
return false;
}
I think what do you want is to get an array from your Mongo collection, correct me if I am wrong.
I am also assuming that Mongo query runs successfully, and returns the records correctly. then you can use toArray function to get array in callback.
// let's say Furniture is your collection
let furniture = Furniture.find({});
let details = [];
furniture.toArray((err, array) => {
if (err) return;
details = array; // now details has your collections' documents
});
For more refer this
Let me know if this is not what you were looking for.
I think you're trying to get a flat array of full details. If my assumption is correct, you could try my solution here:
var fulldetails=[];
for (var i = 0; i < details.length; i++) {
var prjct_id=details[i]._id;
projectimage.find({projectId: prjct_id}).toArray(function(err, data){ //convert data to array first
console.log(data);
fulldetails.concat(data); // concat data to fulldetails to get a flat array
});
}

push object to $scope index [0] object

I have a requirement where I need to push Id's of a scope into one more Variable.
Details
$scope.designView = data.d.results;
which will contains some Information.
Format of $scope.designView
$scope.designView[..]
legth 11
[0]
[1]
Guid
ID
id
Image
Now I Would like to loop through each object in that particular $scope and push to new $scope or variable in which items should be placed in one object
In the following way
Var IdInformation = [1,2,5,67,34];
I have tried this with slice, push and unshift buts doesn't worked.
angular.forEach($scope.designer, function (Dsteps) {
{
stepInformation.unshift(Dsteps.Id); //failed
stepInformation.splice(0, 0, Dsteps.Id); // failed
stepInformation.push({
StepOrder: Dsteps.Id /// Failed
});
}
});
Please provide me the Idea how to achieve it
Thanks in advance
Try with map:
var IdInformation = $scope.designer.map(function(Dsteps) {
return Dsteps.Id;
});

Resources