This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Loop through an array in JavaScript
(46 answers)
Closed 3 years ago.
I have the following data:
const temp = {
"_id" : "5def6486ff8d5a2b1e52fd5b",
"data" : {
"files" : [
{
"path" : "demo1.cpp",
"lines" : [
{
"line" : 18,
"count" : 0
}
]
},
{
"path" : "file2/demo2.cpp",
"lines" : [
{
"line" : 9,
"count" : 0
}
]
}
]
}
}
Now, I want to access the path, and line variable inside each of the files. I am still learning using JS and pretty new with Object.keys.
I have this:
Object.keys(temp.data.files).forEach(file => console.log(file));
This simply prints 0 and 1. Where am I going wrong in this?
This is because temp.data.files is an array. Object.keys is used to loop through Object.
Try this:
const temp = {
"_id": "5def6486ff8d5a2b1e52fd5b",
"data": {
"files": [
{
"path": "demo1.cpp",
"lines": [
{
"line": 18,
"count": 0
}
]
},
{
"path": "file2/demo2.cpp",
"lines": [
{
"line": 9,
"count": 0
}
]
}
]
}
}
temp.data.files.forEach(file => console.log("path ", file.path, " lines ", file.lines));
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 months ago.
Improve this question
Given this input:
const paths = ["src", "src/components", "src/components/index.ts", "src/utils", "src/configuration/config.ts", "another/file.ts"];
I need to create a function or a data structure that returns a Tree with the following structure.
[
{
"id": "src",
"level": 1,
"childrens": [
{
"id": "src/components",
"level": 2,
"childrens": [
{
"id": "src/components/index.ts",
"level": 3,
"childrens": []
}
]
},
{
"id": "src/utils",
"level": 2,
"childrens": []
},
{
"id": "src/configuration",
"level": 2,
"childrens": [
{
"id": "src/configuration/config.ts",
"level": 3,
"childrens": []
}
]
}
]
},
{
"id": "another",
"level": 1,
"childrens": [
{
"id": "another/file.ts",
"level": 2,
"childrens": []
}
]
}
]
I tried everything but I can't make it work, so if anyone can help I would appreciate it a lot.
Thank you.
First, here's the solution based on this answer: https://stackoverflow.com/a/57344801/3807365.
Explanation below.
const paths = ["src", "src/components", "src/components/index.ts", "src/utils", "src/configuration/config.ts", "another/file.ts"];
let agg = {
temp: []
};
paths.forEach(path => {
path.split('/').reduce((agg, part, level, parts) => {
if (!agg[part]) {
agg[part] = {
temp: []
};
agg.temp.push({
id: parts.slice(0, level + 1).join("/"),
level: level + 1,
children: agg[part].temp
})
// console.log(agg)
}
return agg[part];
}, agg)
})
var result = agg.temp;
console.log(result)
.as-console-wrapper {
max-height: 100% !important;
}
Explanation:
Given a path (splitted to parts) and the result which is an empty array []
we are building this kind of object (helper object!):
{
"src" : {
"utils" : {
"file.ts" : {}
},
"components" : {
"file.ts" : {}
}
},
"another": {
"file.ts" : {}
}
}
We do this step by step as we go on each part of the path.
And we do this to each path building this lovely tree.
Simple enough.
But as we do, we are creating arrays in the result object (which is under property temp) - arrays of items of the same level in the format {id, level, children}.
Finally, we ignore this entire helper tree and only return the first level array - which is the result (under property temp).
Once you realize this, you can see the possible error in this method. Can you spot it? What kind of path name will "mess" with the result?
This question already has answers here:
Retrieve only the queried element in an object array in MongoDB collection
(18 answers)
Closed 2 years ago.
A document contains an array of object each object contains a key i want to find all the object that matches the key in mongoose.
Below is the sample schema:
const TalentSchema = new mongoose.Schema({
name: String,
dev_task: [
{
development_training: {
type: mongoose.Schema.Types.ObjectId,
ref: 'TrainingModule',
},
developlink: String,
},
],
})
I want to match the document that have development_training to given Id.
How can i do that ?
Update :
Sample Data
[
{
"name": "name1",
"dev_task": [
{
"development_training": 1,
"developlink": ""
},
{
"development_training": 2,
"developlink": ""
}
]
},
{
"name": "name2",
"dev_task": [
{
"development_training": 1,
"developlink": ""
}
]
},
]
It should return This : -
[
{
"_id": ObjectId("5a934e000102030405000000"),
"dev_task": [
{
"developlink": "",
"development_training": 1
}
],
"name": "name1"
},
{
"_id": ObjectId("5a934e000102030405000001"),
"dev_task": [
{
"developlink": "",
"development_training": 1
}
],
"name": "name2"
}
]
As explained into docs, mongo uses dot notation.
MongoDB uses the dot notation to access the elements of an array and to access the fields of an embedded document.
And this is exactly we want.
So to access your document you need to do dev_task.development_training into find query in this way:
db.collection.find({
"dev_task.development_training": 1
})
Example here
Note that using mongoose is the same query:
yourModel.findOne({"dev_task.development_training": yourId}).then(result => {/*...*/})
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 4 years ago.
I am new to javascript(json) I want to process each json object,the example prototype is given below please help me to solve the problem,I need to console it each room number given in json sample below
how can I loop through the each item in json array so that I can get individual json element and console it on browser window
let data = [
{
"king" :[
{
"id" : 1,
"room_no" : 101,
"price" : 2000
},
{
"id" : 2,
"room_no" : 102,
"price" : 3000
},
]
}
]
sorry for my bad english
Is this what you are looking for?
let data = [{
"king": [{
"id": 1,
"room_no": 101,
"price": 2000
},
{
"id": 2,
"room_no": 102,
"price": 3000
},
]
}]
data[0].king.forEach(item => console.log(item.room_no));
This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 8 years ago.
I need to traverse a JavaScript object with a stored string.
Sample string
var x = "Desserts"
Sample Object
{
"dataset":
{
"Categories" :
[
{
"Desserts" :
[
"Sweets","Ice Creams","Pastry"
]
} ,
{
"Juices and Beverages" :
[
"Cold","Hot","Fresh","Sodas"
]
}
}
}
If I traverse the object as dataset.Categories.x, it doesn't work[returns undefined] . How can I do this?
You should use dataset.Categories[0][x] instead of dataset.Categories[0].x
Take a look at : dot notation or the bracket notation
var x = "Desserts",
data = {
"dataset": {
"Categories": [{
"Desserts": ["Sweets", "Ice Creams", "Pastry"]
}, {
"Juices and Beverages": ["Cold", "Hot", "Fresh", "Sodas"]
}]
}
}
alert(data.dataset.Categories[0][x]);
var obj = {
"dataset": {
"Categories": [{
"Desserts": ["Sweets", "Ice Creams", "Pastry"]
}, {
"Juices and Beverages": ["Cold", "Hot", "Fresh", "Sodas"]
}]
}
}
var x = 'Desserts';
var val = obj.dataset.Categories[0][x];
console.log(val);
JSFIDDLE.
This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
(3 answers)
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 9 years ago.
I am creating a list by fetching values from a JSON file. It is a nested JSON and the list items are- "Thriller","Fiction" which are basically keys for the next level.
on click of the item I'm passing its name(i.e. Thriller/fiction) to another function...
var val = thriller.
Now I need to fetch the value(i.e. "book" & bookname) corresponding to the passed key in this new function. I'm not able to do so using dot operator-
data.library.val not working..
If anybody has worked on something similar..please help..
JSON:
{ "library": [
{
"Thriller": [
{ "book": "ABC" },
{ "book": "DEF" }
]
},
{
"Fiction": [
{ "book": "GHI" },
{ "book": "JKL" }
]
},] }
Code snippet:
$.getJSON('resources/abc.json', function(data){
var i = data.library;
$("#menuList1").css('display','block');
$(i).each(function(key, value){
$.each(value, function(key, value){
console.log(key);
$("#menuList1").append(''+key+'');
});
}); });
Use data.library[key]
MDN Documentation
Your Json is not valid, this },] specially. A good version :
{
"library": [{
"Thriller": [{
"book": "ABC"
}, {
"book": "DEF"
}]
}, {
"Fiction": [{
"book": "GHI"
}, {
"book": "JKL"
}]
}]
}
you can refer the website http://jsonlint.com for validating your json.