Search inside an object from the req.query - javascript

I have a nested object displayed in my view and i want to search in it from the query like this :
http://localhost:3000/test?$folder=folder
My object is like this :
const test = {
"item": [
{
"name": "folder",
"item": [{
"name": "subFolder",
"item": [
{
"name": "subFolderTest1",
"item": [{
"path": "/",
"items": [{
"method": "GET",
}]
}]
},
{
"name": "subFolderTest2",
"item": [{
"path": "/",
"items": [{
"method": "GET",
}]
}]
}
]
}]
}
]
}
If i have http://localhost:3000/test?$folder=folder then i would have :
{
{
"name": "subFolder",
"item": [{},{}]
}
}
And if i have http://localhost:3000/test?$folder=folder/subFolder then i will have :
{
{
"name": "subFolderTest1",
"item": [{}]
},
{
"name": "subFolderTest2",
"item": [{}]
}
}
I know how to get what's inside my query and what the user's input but i don't how to search and display from something which is already displayed.

If you already have your query string you could split it by the "/" character. Use the first name to find your first item, the second name to find the second, and so on.
var folder = "folder/subFolder";
var path = folder.split("/");
var currentItem = test["item"];
// Get each name you are looking for
path.forEach(function(name) {
// get each entry of the current item
currentItem.forEach(function(entry) {
// if the name of the entry is the same as the
// name you are looking for then this is the
// next item you are looking for
if (entry.name == name) {
currentItem = entry["item"];
}
});
});
// now currentItem should be the entry specified by your path
You will still have to add code to handle situations like not having the name you are looking for in your current item, or having multiple entries with the correct name, and so on. I just kept it simple for the sake of clarity.

Related

Iterate through array of objects,not giving required output

given code
[
{
"data": [
{
"text_name": "test",
"text_url": "https://www.news18.com/topics/gold-prices/1",
"is_new": "1"
},
{
"text_name": "test2",
"text_url": "https://www.news18.com/topics/gold-prices/2",
"is_new": "0"
}
],
"slug": "bollywood",
"heading": "testing",
"status": "1",
"is_open_new": "1",
"order_data": "2",
"section_dropdown": "bollywood"
}
]
I want to iterate through this given code snippet and get the data.
const trendingTopicsData = trendingTopics.data
but this is showing null
Since the object in the snippet is an array, first you have to get the index of the item you want to work with (in this case the first item — index 0). Then you can iterate through the data array however you want (loop, forEach, map etc.).
Try:
const trendingTopicsData = trendingTopics[0].data
Here it is as a runnable snippet:
const trendingTopics = [
{
"data": [
{
"text_name": "test",
"text_url": "https://www.news18.com/topics/gold-prices/1",
"is_new": "1"
},
{
"text_name": "test2",
"text_url": "https://www.news18.com/topics/gold-prices/2",
"is_new": "0"
}
],
"slug": "bollywood",
"heading": "testing",
"status": "1",
"is_open_new": "1",
"order_data": "2",
"section_dropdown": "bollywood"
}
]
// Get trending topics data array
const trendingTopicsData = trendingTopics[0].data;
console.log("Data array:", trendingTopicsData)
// Iterate through each of the items in the data array
trendingTopicsData.forEach((dataItem, index) => console.log(`Data item #${index}:`, dataItem));
The object you are trying to access is inside an array. You will have to loop through the array
trendingTopics.forEach(topic => {
// do something with topic.data
})

Merge a Product Config JSON with Generic Config JSON- Issue While Merging Arrays inside it

I have 2 different Json files
1: a Deaflut JSON file
2: A Product Based JSON file
I need to merge them together in such a way that if a feature in default is not in a product that needs to be added to product config from default one.
for this merge, I used "lodash.mergewith" https://www.npmjs.com/package/lodash.mergewith.
so this is now taking care of the merge, But the file contains multiple nested JSON arrays inside it.
to handle that there is an option to use a customizer method that can handle array merge as mentioned in the usage of lodash.mergewith. I need a customizer that can find the Label from Deaflut and compare it with the Product if the Product has the same Label value then replace the URL with the Product URL. else if the Label is not in Product config, then use it from default as it is.
Example
Default config.json:-links is an array of this json with path : object►login►options►sections►2►links
"links": [{
"url": "www.google.com",
"label": "Lable1"
},
{
"url": "www.google.com",
"label": "Label2"
},
{
"url": "www.google.com",
"label": "Label3"
},
{
"url": "www.google.com",
"label": "Label4"
}
]
Productconfig.json:- links is an array inside this of the path: object►login►options►sections►2►links
"links": [{
"url": "www.product1.com",
"label": "label1"
},
{
"url": "www.product2.com",
"label": "Label2"
}
]
** after merge mergedconfig.json "Links" need to be like this.**
"links": [{
"url": "www.product1.com",
"label": "Label1"
},
{
"url": "www.product2.com",
"label": "Label2"
},
{
"url": "www.google.com",
"label": "Label3"
},
{
"url": "www.google.com",
"label": "Label4"
}
]
The main concern is this Array is coming inside a JSON file inside some JSON objects
like eg if the Array is inside links[] it will be in a path like : object►login►options►sections►2►links[]. and this Links Array similarly present inside in some other paths eg: object►register►options►sections►2►links[]
So I need to figure out all the Array like this and for each of the Arrays, I need to perform this action.
Just use Array.map and Array.find:
let links= [
{
"url": "www.google.com",
"label": "Label1"
},
{
"url": "www.google.com",
"label": "Label2"
},
{
"url": "www.google.com",
"label": "Label3"
},
{
"url": "www.google.com",
"label": "Label4"
}
];
let plinks= [{
"url": "www.product1.com",
"label": "label1"
},
{
"url": "www.product2.com",
"label": "Label2"
}
];
let results = links.map(lnk=>{
plnk = plinks.find(pl=>pl.label.toLowerCase()===lnk.label.toLowerCase());
return plnk || lnk
});
console.log(results);
for clean access to nested JSON keys you can use ES like this:
let a = {
b: {
c: [1,2,3]
}
};
let {c} = a?.b;
console.log(c);

Underscore.js where() function issue with searching json objects

I have a json collection stored as {"books": [{...}, ... ]} in a file. "books" is a list of json objects where each is a book. For example:
{
"books": [
{
"items": [
{
"id": "jD8iswEACAAJ",
"volumeInfo": {
"industryIdentifiers": [
{
"type": "ISBN_10",
"identifier": "0984782850"
},
{
"type": "ISBN_13",
"identifier": "9780984782857"
}
],
},
}
]
},
]
}
I have a need to read the json using _.where, specifically search every item in the collection for the "identifier" value of "type": "ISBN_10". Then return the full json object aka {"items": [...]}.
Suppose req.params.id is the "identifier" value (i.e. 0984782850).
This piece of code is not working
var _ = require('underscore');
...
app.get('/api/books/:id', function(req, res) {
var book = _.where(booksData.books.items[0].volumeInfo.industryIdentifiers[0], {identifier: req.params.id});
res.json(book);
});
it is returning
TypeError: Cannot read property '0' of undefined at position 43
The file has valid json, I have tried
var book = _.where(booksData.books, {items[0].volumeInfo.industryIdentifiers[0].identifier: req.params.id});
which also does not work
There is always one item in "items" and the ISBN_10 identifier is the first item in "industryIdentifiers" hence items[0].volumeInfo.industryIdentifiers[0].identifier
What am I doing wrong?
*EDIT: I tried with industryIdentifiers, but response is [ ]
Don't use industryIdentifiers[1]. You want to search the entire industryIdentifiers array, not a single object.
var book = _.where(booksData.books[0].items[0].volumeInfo.industryIdentifiers, {identifier: req.params.id})[0];
You also need books[0], since books is also an array.
const booksData = {
"books": [
{
"items": [
{
"id": "jD8iswEACAAJ",
"volumeInfo": {
"industryIdentifiers": [
{
"type": "ISBN_10",
"identifier": "0984782850"
},
{
"type": "ISBN_13",
"identifier": "9780984782857"
}
],
},
}
]
},
]
};
var book = _.where(booksData.books[0].items[0].volumeInfo.industryIdentifiers, {identifier: "0984782850"})[0];
console.log(book);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>

Updating MongoDB nested array using same path as the search query

I have the following problem, I want to update a document with a path id.metadata.panels.items where panels is an array and items is an array. My search query looks at the items and displays only those that match the criteria of metadata.panels.items.member.type: 'owner' - then I want to update the 'owner to 'account'.
When I am trying to update having the search path same as update path I get an error message saying: cannot use the part metadata.panels.items.member.type to traverse the element.
The documents have their own
How can I resolve this problem?
I have already tried to go through the collection using nested forEach statements to iterate through each of the arrays but I am not sure what to do next.
var records = db.getCollection('sample').find({"metadata.panels.items.member.type":"
[owner]"})
records.forEach(function(id) {
var newFields = [];
metadata.panels.forEach(function(panel, panelIndex){
panels.items.forEach(function (item, itemIndex) {
})
})
})
Sample document structure:
{
"panels": [{
"name": "categories",
"items": [{
"member": {
"type": "[Owner]",
"subtype": "[Contractor]"
},
"format": {
"members": {}
}
}]
},
{
"name": "localisation",
"items": [{
"member": {
"city": "NY",
"state":"NY"
}
}]
}]
}
Expected result:
{
"panels": [{
"name": "categories",
"items": [{
"member": {
"type": "[Account]",
"subtype": "[Contractor]"
},
"format": {
"members": {}
}
}]
},
{
"name": "localisation",
"items": [{
"member": {
"city": "NY",
"state":"NY"
}
}]
}]
}
I figured it out.
var newFields = [];
var records = db.getCollection('sample').find({"metadata.panels.items.member.type":"
[owner]"})
records.forEach(function(id) {
metadata.panels.forEach(function(panel, panelIndex){
panels.items.forEach(function (item, itemIndex) {
// I have generated update statements as strings
// first list is always position 0 and this goes to the statement
// second list get's populated from itemIndex
// added them to the newFields list
})
})
})
newFields.forEach(function(i){
eval(i)
})

i need to convert array value to json in jquery [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
i have array value. need to convert this array value into json format. example is given bleow
Sample Array
[Management Portal!#!#Production Issue Handling!#!#/IONSWeb/refDataManagement/searchDynamicScripts.do, Management Portal!#!# Event Browser!#!#/IONSWeb/orderManagement/eventBrowser.do, Management Portal!#!# Order Workflow!#!#/IONSWeb/orderManagement/SearchOrdersWorkflow.do, ADMINISTRATION!#!#Admin Message!#!#/IONSWeb/userManagement/getMessageForBroadcast.do, ADMINISTRATION!#!#Audit!#!#/IONSWeb/userManagement/auditManagement.do, ADMINISTRATION!#!#Locks!#!#/IONSWeb/userManagement/lockSearch.do, ADMINISTRATION!#!#Queue!#!#/IONSWeb/GroupManagement/begin.do, ADMINISTRATION!#!#Role!#!#/IONSWeb/userManagement/goToRolePage.do, ADMINISTRATION!#!#Routing Rule!#!#/IONSWeb/ruleManagement/showRules.do, ADMINISTRATION!#!#Task Code!#!#/IONSWeb/ManageTaskCode/begin.do, ADMINISTRATION!#!#Trigger OutEvent!#!#/IONSWeb/triggerOutEvent.jsp, ADMINISTRATION!#!#User!#!#/IONSWeb/userManagement/begin.do, ADMINISTRATION!#!#Refresh Application Cache!#!#/IONSWeb/userManagement/refreshApplnCache.do]
sample Json
{
"name": "Administration",
"sub": [
{
"name": "Add Order",
"url": "/IONSWeb/userManagement/auditManagement.do"
},
{
"name": "Infrastructure sonet Add Order ",
"url": "/IONSWeb/userManagement/auditManagement.do"
},
{
"name": "fGNS Add Order",
"url": "/IONSWeb/userManagement/auditManagement.do"
}
]
}
Please anyone help on this
I think you want to do something like this. Split the string, get out the first element, that will be the name, and iterate through all the elements. Every even value will be the name, and every odd an url.
When it is odd, then add it to the sub array. Thats it.
var string = 'Management Portal!#!#Production Issue Handling!#!#/IONSWeb/refDataManagement/searchDynamicScripts.do, Management Portal!#!# Event Browser!#!#/IONSWeb/orderManagement/eventBrowser.do, Management Portal!#!# Order Workflow!#!#/IONSWeb/orderManagement/SearchOrdersWorkflow.do, ADMINISTRATION!#!#Admin Message!#!#/IONSWeb/userManagement/getMessageForBroadcast.do, ADMINISTRATION!#!#Audit!#!#/IONSWeb/userManagement/auditManagement.do, ADMINISTRATION!#!#Locks!#!#/IONSWeb/userManagement/lockSearch.do, ADMINISTRATION!#!#Queue!#!#/IONSWeb/GroupManagement/begin.do, ADMINISTRATION!#!#Role!#!#/IONSWeb/userManagement/goToRolePage.do, ADMINISTRATION!#!#Routing Rule!#!#/IONSWeb/ruleManagement/showRules.do, ADMINISTRATION!#!#Task Code!#!#/IONSWeb/ManageTaskCode/begin.do, ADMINISTRATION!#!#Trigger OutEvent!#!#/IONSWeb/triggerOutEvent.jsp, ADMINISTRATION!#!#User!#!#/IONSWeb/userManagement/begin.do, ADMINISTRATION!#!#Refresh Application Cache!#!#/IONSWeb/userManagement/refreshApplnCache.do';
var pieces = string.split('!#!#');
var first = pieces[0];
//Get out the first one, that will be the key
pieces.shift();
//Create the object
var object = {
'name': first,
'sub': []
};
//Iterate through elements
var i = 0;
var sub = [];
$.each(pieces, function (idx, piece) {
if (i % 2 == 0) {
sub['name'] = piece;
} else {
sub['url'] = piece;
object.sub.push(sub);
}
i++;
});
console.log(object);
Try something like this:
Fiddle: https://jsfiddle.net/ug85d7o7/6/
var jsonData = [],
item, name,
subItem, subUrl,
i, j,
a = [
"Management Portal!#!#Production Issue Handling!#!#/IONSWeb/refDataManagement/searchDynamicScripts.do",
"Management Portal!#!# Event Browser!#!#/IONSWeb/orderManagement/eventBrowser.do",
"Management Portal!#!# Order Workflow!#!#/IONSWeb/orderManagement/SearchOrdersWorkflow.do",
"ADMINISTRATION!#!#Admin Message!#!#/IONSWeb/userManagement/getMessageForBroadcast.do",
"ADMINISTRATION!#!#Audit!#!#/IONSWeb/userManagement/auditManagement.do",
"ADMINISTRATION!#!#Locks!#!#/IONSWeb/userManagement/lockSearch.do",
"ADMINISTRATION!#!#Queue!#!#/IONSWeb/GroupManagement/begin.do",
"ADMINISTRATION!#!#Role!#!#/IONSWeb/userManagement/goToRolePage.do",
"ADMINISTRATION!#!#Routing Rule!#!#/IONSWeb/ruleManagement/showRules.do",
"ADMINISTRATION!#!#Task Code!#!#/IONSWeb/ManageTaskCode/begin.do",
"ADMINISTRATION!#!#Trigger OutEvent!#!#/IONSWeb/triggerOutEvent.jsp",
"ADMINISTRATION!#!#User!#!#/IONSWeb/userManagement/begin.do",
"ADMINISTRATION!#!#Refresh Application Cache!#!#/IONSWeb/userManagement/refreshApplnCache.do"
];
for(i=0; i<a.length; i++)
{
item = a[i].split("!#!#");
name = item[0];
subName = item[1];
subUrl = item[2];
subItem = null;
for (j=0; j<jsonData.length; j++)
{
if (jsonData[j].Name == name)
{
subItem = jsonData[j].sub;
break;
}
}
if (!subItem)
{
jsonData.push({"Name" : name, "sub" : [] });
subItem = jsonData[jsonData.length-1].sub;
}
subItem.push({"Name" : subName, "url" : subUrl });
}
alert(JSON.stringify(jsonData));
Result:
[
{
"Name": "Management Portal",
"sub": [
{
"Name": "Production Issue Handling",
"url": "/IONSWeb/refDataManagement/searchDynamicScripts.do"
},
{
"Name": " Event Browser",
"url": "/IONSWeb/orderManagement/eventBrowser.do"
},
{
"Name": " Order Workflow",
"url": "/IONSWeb/orderManagement/SearchOrdersWorkflow.do"
}
]
},
{
"Name": "ADMINISTRATION",
"sub": [
{
"Name": "Admin Message",
"url": "/IONSWeb/userManagement/getMessageForBroadcast.do"
},
{
"Name": "Audit",
"url": "/IONSWeb/userManagement/auditManagement.do"
},
{
"Name": "Locks",
"url": "/IONSWeb/userManagement/lockSearch.do"
},
{
"Name": "Queue",
"url": "/IONSWeb/GroupManagement/begin.do"
},
{
"Name": "Role",
"url": "/IONSWeb/userManagement/goToRolePage.do"
},
{
"Name": "Routing Rule",
"url": "/IONSWeb/ruleManagement/showRules.do"
},
{
"Name": "Task Code",
"url": "/IONSWeb/ManageTaskCode/begin.do"
},
{
"Name": "Trigger OutEvent",
"url": "/IONSWeb/triggerOutEvent.jsp"
},
{
"Name": "User",
"url": "/IONSWeb/userManagement/begin.do"
},
{
"Name": "Refresh Application Cache",
"url": "/IONSWeb/userManagement/refreshApplnCache.do"
}
]
}
]

Categories