How to print an array inside object that is coming from database? - javascript

I am trying to print an array "data" inside an object "clientData" but the problem is I cant access the array inside before it loads from the database, it gives me an error "Property 'data' does not exist on type '{}'". How do I extract that array without specifying?
this.adnService.getClient().subscribe((result) => {
if (result === null) {
this.empty = true;
}
this.clientData = result;
console.log(this.clientData);
console.log(this.clientData.data[0].client_id);
})
Below is the clientData stringify output
{
"status": "pass",
"data": [
{
"client_id": "u616672",
"client_name": "Client 123"
}
]
}

this.adnService.getClient().subscribe((result) => {
if(result && result != ""){
this.clientData = result;
console.log(this.clientData);
console.log(this.clientData.data[0].client_id);
}else{
this.empty = true;
}
})
(or)
console.log(this.clientData?.data[0].client_id);

Related

Map function in JSON array

I want to find an object from a JSON array. My code is working fine with the object found. But the issue is what if the employee id is not? My code console's "not found" two times. Kindly guide me on what the issue is with my code.
var E_ID
let empArray = [
{
"employee": {
"employee_ID": 16,
"employee_designation": "Node.js",
"employee_FirstName": "John",
"employee_lastName": "Doe",
}
},
{
"employee": {
"employee_ID": 17,
"employee_designation": "Full Stack",
"employee_FirstName": "Samual",
"employee_lastName": "Smith",
},
}
]
function search_EmployeeByID(E_ID) {
empArray.map(item => {
if (item.employee.employee_ID == E_ID) {
console.log(item.employee)
return true
}else {
console.log("not found")
return false
}
})
}
E_ID = parseInt(prompt("Enter Employee_ID to search for:"))
search_EmployeeByID(E_ID);`
The if statement should not be inside find(). find() will return the matching element, or null if it's not found. So test the return value.
function searchEmployeeByID(e_id) {
let emp = empArray.find(e => e.employee.employee_ID == e_id);
if (emp) (
console.log(emp.employee);
return true;
} else {
console.log("not found");
return false;
}
}

How to reference the key from json with node.js

How would I access the following json data
"users":{
"2211392761":{"username":"user1"},
"14300995184":{"username":"user2"},
"2781554712":{"username":"user3"},
"3554341":{"username":"user4"},
"202611":{"username":"user5"},
"17754300653761":{"username":"user6"}
}
I have this so far and I am aware it is completely wrong:
Object.keys(jsonevents["events"]).forEach(function(key) {
if(eventName == jsonevents["events"][key]["name"]){
if(jsonevents["events"][key]["users"]){
if(jsonevents['events'][key]["users"][message.author.id]){
delete jsonevents['events'][key]["users"][message.author.id];
fs.writeFile(eventsjson, JSON.stringify(jsonevents),'utf8');
sayMessage += "```User is no longer part of the event "+jsonevents['events'][key]["name"]+"```";
} else {
sayMessage += "```user is not in the event "+jsonevents['events'][key]["name"]+"```";
}
} else {
sayMessage += "```Why do we have no users```";
}
} else {
//sayMessage += "```No event found```";
}
});
I need to be able to access the key by passing in the username, so user2 would give me 14300995184 so i can then use this to remove the user from the event.
You can search through the Object.entries with find() and return the right object. It will return an array of key/value the key will be what you're after:
let users = {
"2211392761":{"username":"user1"},
"14300995184":{"username":"user2"},
"2781554712":{"username":"user3"},
"3554341":{"username":"user4"},
"202611":{"username":"user5"},
"17754300653761":{"username":"user6"}
}
let found = Object.entries(users).find(([key, value]) => value.username === "user2")
console.log(found && found[0]) // found is undefined if not found
You can iterate over the entries (key-value pairs) of the users object, and use .find to find the username that matches the one you're trying to find. The first item in the entry (the key) will be what you're looking for:
const obj = {
"users": {
"2211392761": {
"username": "user1"
},
"14300995184": {
"username": "user2"
},
"2781554712": {
"username": "user3"
},
"3554341": {
"username": "user4"
},
"202611": {
"username": "user5"
},
"17754300653761": {
"username": "user6"
}
}
}
const findEntry = usernameToFind => {
const foundEntry = Object.entries(obj.users)
.find(([, { username }]) => username === usernameToFind);
if (foundEntry) return foundEntry[0];
};
console.log(findEntry('user5'));
console.log(findEntry('userthatdoesntexist'));

How the java script complex object and complex array iterate?

Below is running code snippet for the javascript object and array.
I have one jsonObj and here the ResultElementLevel could be the array or
object.
According to I just put if else condition and compare if Array and 'object'.
My question is,How would it be possible without if else condition?
can we write one function which compare object and Array inside single if.
The jsonObj is populating dynamically.
Here it would be possible CHECK object is also come into the Array or Object.
var jsonObj = {
"Response": {
"Errors": {
"Check": {
"_attributes": {
"id": "51416",
"name": "lucyocftest090601"
},
"CheckLevel": {
},
"ResultElementLevel": {
"_text": "Line No (2) [Missing Reporting Category] "
}
}
},
"Success": {
}
}
}
iterateObjorArr(jsonObj);
function iterateObjorArr(jsonObj){
let checkArr = jsonObj.Response.Errors.Check;
let checkID = checkArr._attributes.id;
let checkName = checkArr._attributes.name;
let status = 'failed';
let resultElementLevel = checkArr.ResultElementLevel;
let errorUploadArr = [];
let errorUploadObj;
if (Array.isArray(resultElementLevel)) {
resultElementLevel.map(function (data, index) {
errorUploadObj = {
'id': checkID,
'checkName': checkName,
'status': status,
'errors/warnings': data._text
};
errorUploadArr.push(errorUploadObj);
});
} else {
if (typeof (resultElementLevel) === 'object') {
errorUploadObj = {
'id': checkID,
'checkName': checkName,
'status': status,
'errors/warnings': resultElementLevel._text
};
errorUploadArr.push(errorUploadObj);
}
}
console.log("errorUploadArr", errorUploadArr);
}
You can test to see if resultElementLevel has the length property or not using hasOwnProperty(). Arrays have a length while objects do not (generally):
if (resultElementLevel.hasOwnProperty('length')) {
// Handle it as an array
} else {
// Handle as an object
}
This will, however, only work if the object assigned to resultElementLevel is guaranteed to not have a length property.
My question is,How would it be possible without if else condition? can we write one function which compare object and Array inside single if.
I don't think you'd want to get rid of the condition, but being able to deal with the passed data the same way, wether it's an array, a single item, or null/undefined
You could normalize the data first
function toArray(value){
return value == null? []:
Array.isArray(value)? value:
//isArrayLike(value)? Array.from(value):
[value];
}
//Objects that look like Arrays
function isArrayLike(value){
return value !== null && typeof value === "object" && value.length === (value.length >>> 0);
}
so that from here on, you always deal with an Array:
let errorUploadArr = toArray(checkArr.ResultElementLevel)
.map(function(item){
return {
id: checkID,
checkName: checkName,
status: status,
"errors/warnings": item._text
};
});
var jsonObj = {
Response: {
Errors: {
Check: {
_attributes: {
id: "51416",
name: "lucyocftest090601"
},
CheckLevel: {},
ResultElementLevel: {
_text: "Line No (2) [Missing Reporting Category] "
}
}
},
Success: {}
}
};
iterateObjorArr(jsonObj);
function toArray(value) {
return value == null ? [] :
Array.isArray(value) ? value :
//isArrayLike(value)? Array.from(value):
[value];
}
//Objects that look like Arrays
function isArrayLike(value) {
return value !== null && typeof value === "object" && value.length === (value.length >>> 0);
}
function iterateObjorArr(jsonObj) {
let checkArr = jsonObj.Response.Errors.Check;
let checkID = checkArr._attributes.id;
let checkName = checkArr._attributes.name;
let status = "failed";
let errorUploadArr = toArray(checkArr.ResultElementLevel)
.map(function(data) {
return {
id: checkID,
checkName: checkName,
status: status,
"errors/warnings": data._text
}
});
console.log("errorUploadArr", errorUploadArr);
}
.as-console-wrapper{top:0;max-height:100%!important}

Search for a related json data

How can i find data that is related to the already known data?
( I'm a newb. )
For example here is my json :
[
{ "id": "1", "log": "1","pass": "1111" },
{ "id": 2, "log": "2","pass": "2222" },
{ "id": 3, "log": "3","pass": "3333" }
]
Now i know that "log" is 1 and i want to find out the data "pass" that is related to it.
i've tried to do it so :
The POST request comes with log and pass data , i search the .json file for the same log value and if there is the same data then i search for related pass
fs.readFile("file.json", "utf8", function (err, data) {
var jsonFileArr = [];
jsonFileArr = JSON.parse(data); // Parse .json objekts
var log = loginData.log; // The 'log' data that comes with POST request
/* Search through .json file for the same data*/
var gibtLog = jsonFileArr.some(function (obj) {
return obj.log == log;
});
if (gotLog) { // If there is the same 'log'
var pass = loginData.pass; // The 'pass' data that comes with POST request
var gotPass = jsonFileArr.some(function (obj) {
// How to change this part ?
return obj.pass == pass;
});
}
else
console.log("error");
});
The problem is that when i use
var gotPass = jsonFileArr.some(function (obj) {
return obj.pass == pass;
});
it searches through the whole .json file and not through only one objekt.
Your main problem is that .some() returns a boolean, whether any of the elements match your predicate or not, but not the element itself.
You want .find() (which will find and return the first element matching the predicate):
const myItem = myArray.find(item => item.log === "1"); // the first matching item
console.log(myItem.pass); // "1111"
Note that it is possible for .find() to not find anything, in which case it returns undefined.
The .some() method returns a boolean that just tells you whether there is at least one item in the array that matches the criteria, it doesn't return the matching item(s). Try .filter() instead:
var jsonFileArr = JSON.parse(data);
var log = loginData.log;
var matchingItems = jsonFileArr.filter(function (obj) {
return obj.log == log;
});
if (matchingItems.length > 0) { // Was at least 1 found?
var pass = matchingItems[0].pass; // The 'pass' data that comes with the first match
} else
console.log("error"); // no matches
Using ES6 Array#find is probably the easiest, but you could also do (among other things)
const x = [{
"id": "1",
"log": "1",
"pass": "1111"
}, {
"id": 2,
"log": "2",
"pass": "2222"
}, {
"id": 3,
"log": "3",
"pass": "3333"
}];
let myItem;
for (let item of x) {
if (item.log === '1') {
myItem = item;
break;
}
}
console.log(myItem);

assigning new value to an object in object array in jquery

I have an array of objects
object will be in below format
var newUserDetail={"Age":"21","name":"Vicky","UserId":"198303"};
Now I am trying to compare UserId and replace the values
//usersList contains array of newUserDetail kind of objects
jQuery(usersList).each(function(){
if(this.UserId==newUserDetail.UserId){
this=newUserDetail;
}
});
But it throws an error
Invalid left-hand side in assignment
Set the array entry:
jQuery(usersList).each(function (i) {
if (this.UserId == newUserDetail.UserId) {
usersList[i] = newUserDetail;
return false; //if you want to break the loop
}
});
Try this
$(document).ready(function() {
var newUserDetail = {
"Age": "21",
"name": "Vicky",
"UserId": "198303"
};
var tm = {
"Age": "21",
"name": "Vicky",
"UserId": "198303"
};
$.each(newUserDetail, function(k, i) {
if (i == tm.UserId) {
alert("User ID match");
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Categories

Resources