var productSchema = mongoose.Schema({
user_id:String,
products:[]
});
var Products = mongoose.model('Products', productSchema);
...
...
Products.find({},function(err,docs){
for(var i = 0; i < docs.length; i++){
var f = docs[i].products;
console.log(f);
});
Finally I can consoled this
{ _id: 8017ced8gf73kk25a8d9839x,
user_id: '739265b0dlskca14d8djd1a1',
__v: 0,
products:
[ { color: 'yellow', name: 'A' },
{ name: 'B', color: 'red' } ] }
But what I want is 'yellow' in Array!! not Array data.
I need to access the data in {}.
var f = docs[i].products.color;
And I tried this but it makes error.
If you want it in javascript you can run a loop through inner products array
Products.find({},function(err,docs){
for(var i = 0; i < docs.length; i++){
for(var j in docs[i].products){
if(docs[i].products[j] && docs[i].products[j].color){
console.log(docs[i].products[j].color)
}
}
});
Related
I must populate an array of array of objects to get something like this:
let dataObj = [
[
{ content: "test1"},
{ content: "test2"},
{ content: "test3"}
],
[
{ content: "test4"},
{ content: "test5"},
{ content: "test6"}
]
]
I start from an array of arrays like this:
data = [["test1", "test2", "test3"], ["test4", "test5", "test6"]]
I tried with:
let dataObj = <any>[[{ }]];
for (let i = 0; i < data.length; i++) {
for (let j=0; j < data[i].length; j++) {
dataObj[i][j].content = data[i][j];
}
}
but after populating the first ([0][0]) it stops and the error is an
uncaught in promise...
(I work in Angular-TypeScript)
I tried also with:
dataObj.push(i,j,{content: data[i][j]});
It gets a result but it's completely wrong.
Add an array into the root array.
Add an object into the nested array.
let dataObj: { content: any;[key: string]: any }[][] = [];
for (let i = 0; i < data.length; i++) {
dataObj.push([]);
for (let j = 0; j < data[i].length; j++) {
dataObj[i].push({ content: data[i][j] })
}
}
Alternatively, you can work with .map().
let dataObj: { content: any;[key: string]: any }[][] = [];
dataObj = data.map(x =>
x.map(y => {
return { content: y };
})
);
Sample TypeScript Playground
Anyone can give me any suggestions ? I am trying to add an item in every 2 content. I couldn't see anything wrong with the code but why is the MyAds number repeating in all my ads entries ? it is supposed to start from MyAds0 and adding on.
MyAds2
Content1
Content2
MyAds2
Content3
Content4
MyAds2
Content5
Here is my code
const dummyData = [
{
name: 'Content1',
subtitle: 'Content1'
},
{
name: 'Content2',
subtitle: 'Content2'
},
{
name: 'Content3',
subtitle: 'Content3'
},
{
name: 'Content4',
subtitle: 'Content4'
},
{
name: 'Content5',
subtitle: 'Content5'
},
]
let TheData = InsertContent();
function InsertContent () {
let thisdata = [];
let adscounter = 0;
let tmpData = [ {name:'tmp', subtitle:'tmp'}];
for (let i=0; i < dummyData.length; i++){
if (Number.isInteger(i/2)) {
tmpData[0].name = 'MyAds' + adscounter;
tmpData[0].subtitle = 'My MyAds Sub' + adscounter;
thisdata = [...thisdata, tmpData[0]];
adscounter = adscounter + 1;
}
thisdata = [...thisdata, dummyData[i]];
}
return thisdata;
}
Actually the Problem is not with the logic but with the way you are using object and array with spread operator. You really don't have to use a object at first index in a array Instead you can directly use the object with spread operator to store into the array. I just modified your code to make it work as per your requirements.
const dummyData = [
{
name: 'Content1',
subtitle: 'Content1'
},
{
name: 'Content2',
subtitle: 'Content2'
},
{
name: 'Content3',
subtitle: 'Content3'
},
{
name: 'Content4',
subtitle: 'Content4'
},
{
name: 'Content5',
subtitle: 'Content5'
},
];
let TheData = InsertContent();
console.log(TheData);
function InsertContent () {
let thisdata = [];
let adscounter = 0;
let tmpData = {name:'', subtitle:''};
for (let i=0; i < dummyData.length; i++){
if (Number.isInteger(i/2)) {
tmpData = {
name: 'MyAds' + adscounter,
subtitle : 'My MyAds Sub' + adscounter
};
thisdata = [...thisdata, tmpData];
adscounter = adscounter + 1;
}
thisdata = [...thisdata, dummyData[i]];
}
return thisdata;
}
I am trying to create a nested JSON object using NodeJS. I am getting data from the JIRA software server and trying to map to my application's schema. Below is my application's schema.
schema:
Product:
_id: ObjectId
categories: [Category]
backlog: [Section]
Category:
_id: ObjectId
name: String
color: String
Section:
_id: ObjectId
title: String
backlogItems: [BacklogItem]
BacklogItem:
_id: ObjectId
productId: ObjectId
title: String
description: String
category: Category
acceptanceCriteria: [AcceptanceCriterion]
tasks: [Task]
notes: [Note]
I want to create one category for tasks. For example, if there are two or more issues from JIRA of type "Epic", I want to create only one category and then I want to create an array of BacklogItems but it is giving me below error:
categories: [Category], Category is not defined
Below is what I am trying to do:
function parseResponse(body) {
var data = JSON.parse(body);
result.product = {
id: ObjectID(),
categories: [Category],
backlog: [Section]
};
for (var i = 0; i < data.issues.length; i++) {
var color;
var categoryName;
switch (data.issues[i].fields.issuetype.name) {
case "Story":
color = "green";
break;
case "Epic":
color = "purple";
break;
case "Task":
color = "blue";
break;
case "Bug":
color = "red";
break;
}
var uniqeCategory = [
...new Set(data.issues.map(x => x.fields.issuetype.name))
];
if (uniqeCategory[i] !== data.issues[i].fields.issuetype.name) {
categoryName = uniqeCategory[i];
} else {
categoryName = data.issues[i].fields.issuetype.name;
}
console.log(uniqeCategory);
result.product.backlog.push({
id: ObjectID(),
title: "importer",
backlogItem: []
});
result.product.backlog.backlogItem.push({
id: data.total,
productId: result.product.id,
title: data.issues[i].fields.summary,
description: data.issues[i].fields.description,
category: data.issues[i].fields.issuetype.name,
acceptanceCriteria: [],
tasks: [],
notes: []
});
Can somebody try to tell me what I am doing wrong and How can I create such an object?
PS: I just started working with NodeJS and trying to learn it by doing it.
After some efforts, I tried to create an object. Below is my code.
for (var j = 0; j < issue.fields.attachment.length; j++) {
var note = {
_id: ObjectID(),
createdAt: issue.fields.attachment[j].created,
content: issue.fields.attachment[j].filename,
attachmentUrl: issue.fields.attachment[j].content,
attachmentPreviewUrl: issue.fields.attachment[j].thumbnail
};
notesArray.push(note);
}
/* Creating seaparate notes by taking comments from each JIRA issue and put it in form of note */
for (var k = 0; k < issue.fields.comment.comments.length; k++) {
var note = {
_id: ObjectID(),
createdAt: issue.fields.comment.comments[k].created,
content: issue.fields.comment.comments[k].body,
attachmentUrl: "",
attachmentPreviewUrl: ""
};
notesArray.push(note);
}
/* Creating backlog items */
result.product.backlog.push({
_id: ObjectID(),
productId: result.product._id,
title: issue.fields.summary,
description: issue.fields.description,
category: issue.fields.issuetype.name,
acceptanceCriteria: [],
tasks: [],
notes: notesArray
});
console.log("final", result.product);
});
My Data Array
data:[
0:{
id:1 ,.....
competetion:[
0:{
id: 1....,
match:[
0:{id: 1 ......},
1:{same}
.
.
]
1:{same}]},
2:{same}
.
.
]
},
1:{same},
2:{same}
.
.
.
]
For data[] i able to create a new array(sportarr[]) with pushing elements but i want to create for the same as competetion[] and match[] in the same array sportarr[]
If there any other way to do it please Help me...
My Code: Here i am looping it:
this.sportsSidebar = response.data; // My data Array (this.sportsSidebar)
const arrlength = response.data.length;
for (let i = 0; i < arrlength; i++) {
this.sportarr.push({ // I declared a new array where i want to push the element
id: i,
value: false
});
}
if you want your own content based on the mapping what I will suggest is that first iterate through the array then map each match and competetion and write your own logic inside the map
const arrlength = data.length;
for (let i = 0; i < arrlength; i++) {
let competition = [];
competition = data[i].competetion.map( (val, index) => {
#write your own logic to produce the required outcome
return {
id: index,
value: false
};
});
this.sportarr.push({
id: i,
value: false,
competetion: competition
});
console.log('myarrr...', this.sportarr);
i Appriciate Pathikrit Sanyal and Fahd Lihidheb For the ansers
Here Is my Change according to Pathikrit Sanyal
for (let i = 0; i < arrlength; i++) {
let competition = [];
competition = response.data[i].competetion.map((val, index) => {
let match = [];
match = val.match.map((value, indx) => {
return {
id: indx,
value: false
};
});
return {
id: index,
value: false,
match
};
});
this.sportarr.push({
id: i,
value: false,
competetion: competition
});
console.log('myarrr...', this.sportarr);
}
Now i am getting what i wanted
i am not sure if you are trying to create an array for each nasted array (competetion and match) or not, but here you go
this.sportsSidebar = response.data; // My data Array (this.sportsSidebar)
const competetionList = // Array of competetions
[].concat.apply([], this.sportsSidebar.map(item => item.competetion));
const matchList = // Array of matchs
[].concat.apply([], competetionList .map(item => item.match));
}
I am trying to create a dynamic donut chart as I don’t know how many variables will be coming in but the dataset will be in the 10,000's with between 1 and 20 variables.
I have got my data into an array as below.
How do I create a var for each unique element in the array and its count i.e var 1 = [sys1, 94] or similer so they can be used in the columns and colours config
Original data
res.data[{system:'sys1'},
{system:'sys1'},
{system:'sys2'},
{system:'sys1'},
{system:'sys3'},
{system:'sys3'}]
Getting keys
var array_elements = []
angular.forEach(res.data, function(value, key){
if (array_elements.indexOf(value.system) === -1){
array_elements.push(value.system)
}
})
array_elements = ["sys1", "sys2", "sys3"];
config
var donutData = {
type : 'donut',
colors: {
Cats: $.pfPaletteColors.blue,
Hamsters: $.pfPaletteColors.green,
Fish: $.pfPaletteColors.orange,
Dogs: $.pfPaletteColors.red
},
columns: [
['Dogs', 2],
['Cats', 2],
['Fish', 3],
['Hamsters', 1]
],
You can do something like this:
var data = [{
system: 'sys1'
}, {
system: 'sys1'
}, {
system: 'sys2'
}, {
system: 'sys1'
}, {
system: 'sys3'
}, {
system: 'sys3'
}];
var tmp = {};
data.forEach(function(x) {
tmp[x.system] = (tmp[x.system] || 0) + 1;
});
var keys = Object.keys(graphData);
var finalData = [];
for(var i = 0; i < keys.length; i++) {
var x = [];
x.push(keys[i]);
x.push(graphData[keys[i]]);
finalData.push(x);
}
console.log(finalData);
Fiddle example