I need a little help with a loop in JavaScript.
Please see the JSON data below
{
"blogs":{
"id1":{
"title":"Title 1",
"date":"test_date",
"datestamp":"test_datestamp 1",
"content":"The content",
"url":"https:\/\/www.testlink1.com",
"tags":["move","New"]
},
"id2":{
"title":"Title 2",
"date":"test_date",
"datestamp":"test_datestamp 2",
"content":"The content 2",
"url":"https:\/\/www.testlink2.com",
"tags":["Netherlands","Yellow"]
}
}
}
Next I parse the JSON like below
data = JSON.parse(this.response); //This JSON is the result from an AJAX call to a PHP file
For using the data I do this
for(let id in data.blogs){
console.log(data.posts[id].date);
console.log(data.posts[id].title);
//etc.
}
But how can I loop the tags array inside this loop?
I tried this but with no result
for(let id in data.blogs){
for(let tag in data.blogs.tags){
alert(data.blogs[id].tags[tag]);
}
}
Who can help me with this?
But how can I loop the tags array inside this loop?
You need to identify the blog item currently in the process loop.
Here due example, note the for-in as you wrote or the for-of loop to cycle the items.
const data = {
blogs: {
id1: {
title: 'Title 1',
date: 'test_date',
datestamp: 'test_datestamp 1',
content: 'The content',
url: 'https://www.testlink1.com',
tags: ['move', 'New']
},
id2: {
title: 'Title 2',
date: 'test_date',
datestamp: 'test_datestamp 2',
content: 'The content 2',
url: 'https://www.testlink2.com',
tags: ['Netherlands', 'Yellow']
}
}
}
for (const blogId in data.blogs) {
const blogItem = data.blogs[blogId]
console.log(`looping ${blogItem.title}`)
for (const tag of blogItem.tags) {
console.log(tag)
}
}
for (const blogItem of Object.values(data.blogs)) {
console.log(`looping ${blogItem.title}`)
for (const tag of blogItem.tags) {
console.log(tag)
}
}
Related
I try to merge an array of objects into a single string, but got a bit lost. The input looks like that:
const array = [
{
key: "title",
text: " Example Text title",
},
{
key: "description",
text: "Example Text description",
},
{
key: "video",
text: "Example Text video",
},
];
Expected Output:
"title: Example Text title, description: Example Text description, video: Example Text video"
Thanks for any hint.
Since you want a single string out of this, and not an array, you will want to use Array.forEach to concatenate onto an existing string object, like so:
let outStr = '';
array.forEach((ele, idx) =>
outStr += `${ele.key}: ${ele.text}${idx < array.length ? '' : ', '}`
);
You could also use Array.map like the folks in the comments above suggested, but you will need to join the result to produce a single string at the end.
const array = [
{
key: "title",
text: " Example Text title",
},
{
key: "description",
text: "Example Text description",
},
{
key: "video",
text: "Example Text video",
},
];
let result = "";
array.forEach((object, index) => {
result += `${object.key}: ${object.text}`
if(index < array.length - 1) {
result += ', ';
}
});
console.log(result);
I hope the following is useful for you.
const array = [
{
key: "title",
text: " Example Text title",
},
{
key: "description",
text: "Example Text description",
},
{
key: "video",
text: "Example Text video",
},
];
array.map(item => `title: ${item.text}, description: ${item.text}, video: ${item.text}`).toString()
//'title: Example Text title, description: Example Text title, video: Example Text title,title: Example Text description, description: Example Text description, video: Example Text description,title: Example Text video, description: Example Text video, video: Example Text video'
Hey I'm trying to implement nested drag&drop within re-order sequencesin my MERN app. I working to find ideal approach for mongodb data model and implement to Lexicographic order or linked lists for infinite sub folders. I used Model Tree Structures in this link but every node have limitless children for that require recursion and recursive functions or currying. Documentations not clear enough for make do that.
I want show all tree once and not sohuld appear after than click to arrow icon.There is my doodles for front side generation that working with only one depth such like graph nodes. Maybe Modified Preorder Tree Traversal implementation examples you have for this scenario.
const tree = data => { // immutable array
let ascendants = data.filter(d=>d.parent==null)
let descandants = data.filter(d=>d.parent)
**strong text**
let form = []
ascendants.map(a=>{
let node1 = {...a}; /// copying
let node1Children = [];
descandants.map(b=>{
let node2 = {...b};
if(node1._id == b.parent){
node1Children.push(node2)
}
})
node1.children = node1Children;
form.push(node1);
})
return form;
}
I cant take result with using $graphLookup because list format is not what i want.Could you give me some mongodb playground or grouping aggregate solutions? Below json examples shown my expecting results. I can do before but hardcode is unapropriate and performless. Is comparing good way?
[
// mongo database
{_id:123, title:'Books', slug:'books', parent:null },
{_id:124, title:'Programming', slug:'programming', parent:null },
{_id:125, title:'JavaScript', slug:'javascript', parent:'programming' },
{_id:126, title:'C++',slug:'cpp', parent:'programming' },
{_id:127, title:'React', slug:'react', parent:'javascript' },
{_id:128, title:'Redux', slug:'redux', parent:'react' },
{_id:129, title:'Toolkit', parent:'redux' },
{_id:130, title:'Saga', parent:'redux' },
{_id:131, title:'Nodejs', parent:'programming' },
{_id:132, title:'Databases', slug:'databases' },
{_id:133, title:'MongoDB', parent:'databases' },
]
[
// what i want
{ title: "Books"},
{ title: "Programming", parent:"computer-science", children: [
{ title: "JavaScript", children: [
{ title: "React", children: [
{ title: "Redux", children: [
{ title: "Saga" },
{ title: "Thunk" },
{ title: "Mobx" },
{ title: "Observable" },
{ title: "Context" },
{ title: "GraphQL" },
{ title: "Toolkit", children:[
{ title: "typescript" },
{ title: "slices", children:[
{ title: "createAsyncThunk" },
{ title: "createSlice" },
] },
] },
] },
{ title: "Nextjs" },
]},
{ title: "Vue", },
{ title: "angular", },
]},
{ title: "C++", },
{ title: "NodeJS", },
] },
{ title: "MongoDB", parent: "databases"},
]
You could create a Map to key your objects by slug. The values per key will be the result objects for parent objects. Include an entry for null, which will collect the top-level elements.
Then iterate the data again to populate children arrays -- when that property does not exist yet, create it on the fly. Finally output the top-level elements.
function makeTree(data) {
let children = []; // Top-level elements
let map = new Map(data.map(({title, slug}) => [slug, { title }]))
.set(null, {children});
for (let {slug, parent, title} of data) {
(map.get(parent || null).children ??= [])
.push(slug ? map.get(slug) : {title});
}
return children;
}
// Your mongodb data:
const data = [{_id:123, title:'Books', slug:'books', parent:null },{_id:124, title:'Programming', slug:'programming', parent:null },{_id:125, title:'JavaScript', slug:'javascript', parent:'programming' },{_id:126, title:'C++',slug:'cpp', parent:'programming' },{_id:127, title:'React', slug:'react', parent:'javascript' },{_id:128, title:'Redux', slug:'redux', parent:'react' },{_id:129, title:'Toolkit', parent:'redux' },{_id:130, title:'Saga', parent:'redux' },{_id:131, title:'Nodejs', parent:'programming' },{_id:132, title:'Databases', slug:'databases' },{_id:133, title:'MongoDB', parent:'databases' }];
console.log(makeTree(data));
I have a page that gets two arrays of input elements and sends them by post request to my app.js:
<input type="text" name="titleAttr[]" > </input>
<input type="text" name="descriptionAttr[]"> </input>
I created a Schema that receives an array with 2 fields, titleAttr and descriptionAttr, which correspond to the <input> elements above:
const mySchema = mongoose.Schema({
titulo: String,
attrs: [{
titleAttr: String,
descriptionAttr: String
}]
});
I can insert the data manually and it works:
MyModel.bulkWrite([ { insertOne : { document: {
title : "TEST",
attrs: [
{titleAttr : "test 1", descriptionAttr: "This is a test 1"},
{titleAttr: "test 2", descriptionAttr: "This is another test"}
]
} } }
]);
Here is a screenshot of the form .
When the post request is sent from my form and I print it in app.js, I get these results:
console.log(req.body.titleAttr); //result: [ 'test 1', 'test 2' ]
console.log(req.body.descriptionAttr);// result: [ 'This is a test 1', 'This is another test' ]
This code doesn't work:
ConceitoHTML.bulkWrite([ { insertOne : { document: {
titulo : req.body.title,
attrs: [
{
titleAttr: req.body.titleAttr,
descriptionAttr: req.body.descriptionAttr
}
]
} } } ]);
I want to merge my two arrays and insert into MongoDB as an array of objects. How do I generate an array like the following?
const myArray = [
{
titleAttr: req.body.titleAttr[0],
descriptionAttr: req.body.descriptionAttr[0]
},
{
titleAttr: req.body.titleAttr[1],
descriptionAttr: req.body.descriptionAttr[1]
}
]
You can do it with this code below 👇 to get an array as expected what you want:
const {titleAttr, descriptionAttr} = req.body;
const myArray = [];
// check the length first, make sure it's same
if(titleAttr.length === descriptionAttr.length) {
for(let i=0; i<titleAttr.length; i++) {
myArray.push({ titleAttr: titleAttr[i], descriptionAttr: descriptionAttr[i] })
}
}
console.log(myArray); // this is the array result
I hope it's can help you.
I have an object which contains an array of objects called "blocks":
$scope.microsite = {
images: [
{url: "https://unsplash.it/800/400/?image=20"},
{url: "https://unsplash.it/800/400/?image=15"},
{url: "https://unsplash.it/800/400/?image=52"}
],
blocks: []
};
When I add stuff to this array, it behaves perfectly normally:
$scope.addElement = function(a){
if(a=='heroslider'){
var data = {
slides: [
{
id:0,
image:0,
title: "Title",
desc: "Description",
},
{
id:1,
image:1,
title: "Title",
desc: "Description",
},
{
id:2,
image:2,
title: "Title",
desc: "Description",
}
]
};
} else if(a=='threecol'){
var data = {
columns: [
{
title: "Column one",
text: "This is a column for features",
},
{
title: "Column two",
text: "This is a column for features",
}
]
};
}
var element = {
template: a,
data: data
};
$scope.microsite.blocks.push(element);
}
However when I try to remove an object from the array by calling this function on ng-click and passing in the object from an ng-repeat...
$scope.removeElement = function(element){
var x = $scope.microsite.blocks.indexOf(element);
console.log($scope.microsite.blocks[x]);
console.log(x);
$scope.microsite.blocks.splice(x, 1);
}
I am able to get both the correct object and the correct index in my console, but when it goes to splice the array, the last object is always being deleted which is very strange as this should only be happening when the index I'm trying to delete doesn't exist (and therefore would equal -1)
Any ideas why this could be happening?
EDIT: I have also tried using ng-click="microsite.blocks.splice($index, 1)" directly in the element, as well as passing the $index into the function instead of the element. In all cases, the correct index is found, but the result is still the same, only the last entry is ever deleted.
Turns out this was an error with "track by $index" in Angular. After removing "track by $index" from my ng-repeat, splice() functioned normally.
I am making an ajax call that returns some json data. I need to take this data, loop through it and build a new javascript array.
This is what the returned json looks like:
{
query: [ ],
products: 
[

{
title: "title 1",
price: "6.00",
magazine: "magazine name 1",
image: "/p/c/pc_90_cover.jpg",
type: "Magazine",
market: "Technology",
zinio: "http:www.zinio.com",
newsstand: "http://www.link1.php"
},

{
title: "title 2",
price: "6.00",
magazine: "magazine name 2",
image: "/p/c/pc_90_cover.jpg",
type: "Magazine",
market: "Technology",
zinio: "http:www.zinio.com",
newsstand: "http://www.link2.php"
},

{
title: "title 3",
price: "6.00",
magazine: "magazine name 3",
image: "/p/c/pc_90_cover.jpg",
type: "Magazine",
market: "Technology",
zinio: "http:www.zinio.com",
newsstand: "http://www.link3.php"
}
]
}
How do I loop through this data in javascript? This is what I have so far but it is very wrong! - apologies my javascript is not my strongest skill!
var allProducts = $.get("http://localhost:8888/imagine-publishing/web/app_dev.php/api/v1/search/search.json?query=pho", function(data) {
var arrProducts = [
for (var product in allProducts) {
title = product.title,
url = product.url,
label = product.title,
magazine = product.magazine,
image = product.imageThumb,
newsstand = product.newsstand,
googleplay = product.googleplay,
kindle = product.kindle,
barnesnoble = product.barnesnoble,
zinio = product.zinio,
kobo = product.kobo,
waterstones = product.waterstones,
type = product.type,
brandurl = product.brandurl
},
];
});
console.log(arrProducts);
Assuming the JSON is served with the correct Content-Type (application/json), jQuery will automatically parse the JSON and populate the first argument of the callback function with the result.
var arrProducts = data.products;
http://api.jquery.com/jQuery.parseJSON/
jQuery.parseJSON("json string")
Using jQuery's getJSON
http://api.jquery.com/jQuery.getJSON/
$.getJSON(url, function(data){
// Your code goes here
});