findding a key in an object in node.js - json

i have a lookup-table of JSON, i want to search for a specific key in that lookup-table; which could return me the complete object of the match.
Is it possible without any loop or with any built-in liberary.

its JSON, a straight look up for the key.?
var obj = { 'foo' : 'bar', 'fez' : [1,2,3], 'fizz' : { 'baz': true} };
console.log( "'foo' is accessed like " + obj.foo + " -or- " + obj['foo'] )
var fw_table = {"FW_1":{ "tn":"sn_201", "cf": "06.57", "ci": "A1", "di":"048"}, "FW_2":{ "tn":"sn_202", "cf": "06.57", "ci": "A2", "di":"045"}};
function search(fwObj, key, val){
var topKey = Object.keys(fwObj).find((e)=>{ return(fwObj[e][key] === val ) });
console.log(topKey);
return fwObj[topKey];
}
console.log("Find cf:'06.57' : ", search(fw_table, "cf","06.57") );
console.log("Find di:'045' : ", search(fw_table, "di","045") );

Related

Accessing json returning undefined react js

I am trying to grab some json data to display in Ui but when I iterate over it using the map method I keep getting undefined.Any help will be really appreciated.Here is a link on code sandbox https://codesandbox.io/s/late-wood-kx8w2?file=/src/App.js
This line
const [items, setItem] = useState(Object.keys(trees));
is passing the tree keys to the View function and not the actual data. I believe that you meant to pass the data. Your code passes 'name' and 'children' as {items} that then gets displayed by View.js.
The following code shows you how you can parse the tree and get the names and the values. It's incomplete, but it should give you a start on how to do the traversal.
import React, { useState } from "react";
export default function Start(){
const trees = {
name: "root",
children: [
{
name: "child1",
children: [
{ name: "child1-child1", data: "c1-c1 Hello" },
{ name: "child1-child2", data: "c1-c2 JS" }
]
},
{ name: "child2", data: "c2 World" }
]
};
const treesCopy = trees;
function Traverse(tree){
var treesCopy = tree;
var str = [];
for (var prop in treesCopy) {
console.log(prop);
if (prop=="children"){
str = str + "name: "+ prop + ",";
treesCopy = treesCopy[prop][0];
// console.log('New tree: ',treesCopy);
return str + Traverse(treesCopy);
}
str = str + "name: "+ prop +" value: " + treesCopy[prop]+",";
}
return str;
};
const str = Traverse(treesCopy);
return(
<>
{
str ? str.split(",").map(place => <p> {place} </p>)
: ""
}
</>
)
}

Wrong string format when i use persian and english together in Node Js

I have a node js project with MySql database. I have to use Persian data in my DB like:
UserModel = {id: 1200, firstName: 'صابر', lastName: 'سجادی' , nationalCode:'4640147800', displayName: 'saber-sajadi', status: 1, createDateTime: null };
so for run stored procedure i need to convert object to string with this Code:
let objectToString = (object) => {
let _string = "";
let i = 1;
for (let key in object) {
var val = object[key];
_string += (val == undefined || val == null) ? `null` : `'` + val + `' `;
if (i < Object.keys(object).length) {
_string += " , ";
i++;
}
}
return _string;
}
I expect the output of the function to be as follows:
but it return:
1200,'صابر','سجادی','4640147800','saber-sajadi','1',''
Please help me to solve this problem
we can use this function to solve problem:
function wrap(str){ return '\u202B' + str + '\u202C'; }

Create JSON using for loop, Express.js

I'm newbie to express.js. I want to create a JSON using for loop. But the code returns object object. I don't know why. But for a single JSON, it returns as a JSON value. In this code, I have added a function to retrieve my JSON values from mongoDB. Please help me to complete this.
router.get('/', (req, res) => {
Followups.find({}).then(followupData => {
Staffs.find({}).then(staffData => {
Institutions.find({}).then(institutionData => {
var fcount = Object.keys(followupData).length;
var scount = Object.keys(staffData).length;
var icount = Object.keys(institutionData).length;
console.log(icount);
var jsonData = '';
function getStaffData(id) {
return staffData.filter(
function(staffData) {
return staffData._id == id;
}
);
}
function getInstitutionData(id) {
return institutionData.filter(
function(institutionData) {
return institutionData._id == id;
}
);
}
for (i=0; i<fcount; i++)
{
fstaffid = followupData[i].staffid;
fschoolid = followupData[i].schoolid;
staffDetails = getStaffData(fstaffid);
institutionDetails = getInstitutionData(fschoolid);
jsonData += {
staffname : staffDetails[0].achternaam + ' ' + staffDetails[0].voornaam + ' ' + staffDetails[0].tv,
staffplace : staffDetails[0].plaats,
staffphone : staffDetails[0].telefoon,
schoolname : institutionDetails[0].instellingsnaam,
schoolplace : institutionDetails[0].plaatsnaam,
schoolphone : institutionDetails[0].telefoonnummer,
notes : followupData[i].notes,
date : followupData[i].date,
created_at : followupData[i].created_at,
status : followupData[i].seen
}
}
console.log(jsonData);
res.render('followup', {followupData:followupData, jsonData: jsonData});
});
});
});
});
Problem solved by using concat
jsonData = jsonData.concat({
followupid : followupData[i]._id,
schoolid : followupData[i].schoolid,
staffid : followupData[i].staffid,
staffname : staffDetails[0].achternaam + ' ' + staffDetails[0].voornaam + ' ' + staffDetails[0].tv,
staffplace : staffDetails[0].plaats,
staffphone : staffDetails[0].telefoon,
schoolname : institutionDetails[0].instellingsnaam,
schoolplace : institutionDetails[0].plaatsnaam,
schoolphone : institutionDetails[0].telefoonnummer,
notes : followupData[i].notes,
date : followupData[i].date,
created_at : followupData[i].created_at,
status : followupData[i].seen
});
You can display the data of jsonData like:
console.log(JSON.stringify(jsonData));
object object means jsonData is a JSON object, you cannot display a JSON object directly. You must stringify it before doing this.
You may be able to find more about the issue after using JSON.stringify

How to fetch value from json object in angular 6?

I have one json file which contains multiple objects inside another object. I want to fetch data but not using key of that value. I want to iterate there key and values and want to print them dynamically in angular 6.
{
"name" : "abc",
"tags" : "def",
"updated-by" : "ijk",
"property" : {
"description" : "abcd",
"type" : "string"
},
"sources" : {
"input" : {
"type" : "lmn",
"properties" : {
"key" : "opq"
}
}
}
}
Can we iterate objects like we iterates array. If anyone can help?
I would suggest referring this StackOverflow question,
As far as I know, *ngFor can be used not only for arrays but also for Objects.
Hope the above link helps.
Also for the keys whose values contain objects, you could check if the corresponding value of the key is an object.
For instance,
if( (typeof A === "object") && (A !== null) )
where A is the corresponding value of the key. If A is indeed an object, use *ngFor again to iterate over the object.
I haven't tested the following code but I hope you get an overview of what I am trying to say,
#Component({
selector: 'app-myview',
template:
`<div *ngFor="let key of objectKeys(items)">{{key + ' : ' + items[key]}}
<div *ngIf="checkFunction(items[key])">
<div *ngFor="let key2 of objectKeys(items[key])">
{{key2 + ' :' + items[key][key2]}}
</div>
</div>
</div>`
})
export class MyComponent {
objectKeys = Object.keys;
items = { keyOne: 'value 1', keyTwo: 'value 2', keyThree: 'value 3' };
constructor(){}
checkFunction(obj){
if( (typeof obj === "object") && (obj !== null) )
{
return true;
}
else{
return false;
}
}
}
var temp = {
"name" : "abc",
"tags" : "def",
"updated-by" : "ijk",
"property" : {
"description" : "abcd",
"type" : "string"
},
"sources" : {
"input" : {
"type" : "lmn",
"properties" : {
"key" : "opq"
}
}
}
};
flatten the object
var flattenObject = function(ob) {
var toReturn = {};
for (var i in ob) {
if (!ob.hasOwnProperty(i)) continue;
if ((typeof ob[i]) == 'object') {
var flatObject = flattenObject(ob[i]);
for (var x in flatObject) {
if (!flatObject.hasOwnProperty(x)) continue;
toReturn[i + '.' + x] = flatObject[x];
}
} else {
toReturn[i] = ob[i];
}
}
return toReturn;
};
var flat = flattenObject(temp)
Iterate over object just like array
Object.entries(flat).forEach(entry => {
console.log(entry[0] + " => " + entry[1])
})

How to query in mongodb programmatically?

I wannt to create code like this:
var result = Attributes.find({
attribute_name : {
$exist : true,
$in : [1]
}
});
but programmatically, so i ceate code like this:
var genQuery = '{ "' + by + '" : { "$exists" : true, "$in" : [' + data + ']} }';
var result = Attributes.find(genQuery);
but I get error maximum call stack
because result of JSON.parse(genQuery)
{ _id: { '$exists': true, '$in': [ 1 ] } }
How to query in mongodb programmatically?
Your genQuery variable you declare is a String, but you cannot pass strings as selectors or modifiers in find() functions.
You should create an Object to make it works:
var genQuery = {};
//use this notation to declare a new object key depending on a variable
genQuery[by] = {
$exists: true,
$in: [1]
};
var result = Attributes.find(genQuery);