Looping through an array of objects and find a specific key - javascript

I have an array of objects which looks like
data =
[
{
"AccountType":"Client",
"DeploymentList":
{
"-L3y8Kpl5rcvk-81q004":
{
"DeploymentKey":"-L3y8Kpl5rcvk-81q004",
"DeploymentName":"Testing 3"
}
}
},
{
"AccountType":"Client",
"DeploymentList":
{
"-L3yGFxXQ8XbeK8b2GSF":
{
"DeploymentKey":"-L3yGFxXQ8XbeK8b2GSF",
"DeploymentName":"Testing 1"
}
}
}
]
I want to loop through this data and want to find a string. In this data, I want to find
What I have tried so far is
for (let d of this.data) {
for(let a of d.DeploymentList){
if(a.$key==="-L3y8Kpl5rcvk-81q004"){
// Inside the condition
}
}
But it is not working. How I can achieve this ?

You can check if key exists as follows,
for (let d of this.data) {
for(let a of d.DeploymentList){
if(a["-L3y8Kpl5rcvk-81q004"]){
// Inside the condition
}
}

It depends on what you want to do. If you're just trying to find the deployment list item you can do it easily with find
var item = data.find(item => item.DeploymentList["-L3y8Kpl5rcvk-81q004"]);
This will give you the item from your data array with that particular DeploymentList item.
var data =
[
{
"AccountType":"Client",
"DeploymentList":
{
"-L3y8Kpl5rcvk-81q004":
{
"DeploymentKey":"-L3y8Kpl5rcvk-81q004",
"DeploymentName":"Testing 3"
}
}
},
{
"AccountType":"Client",
"DeploymentList":
{
"-L3yGFxXQ8XbeK8b2GSF":
{
"DeploymentKey":"-L3yGFxXQ8XbeK8b2GSF",
"DeploymentName":"Testing 1"
}
}
}
];
var item = data.find(item => item.DeploymentList["-L3y8Kpl5rcvk-81q004"]);
console.log(item);

Related

Find Index from Mapped Objects

Desired output will be like, I want to find last and first index. I'm having trouble in handling this. I'm not be able to get the index from this objects.
{
'13-2-2022' =>[
{
"name":"abc"
"date":"13-2-2022"
},
{
"name":"xyz"
"date":"13-2-2022"
}
]
'15-2-2022' =>[
{
"name":"azx"
"date":"15-2-2022"
},
{
"name":"qwe"
"date":"15-2-2022"
}
]
'16-2-2022' =>[
{
"name":"azx"
"date":"16-2-2022"
},
{
"name":"qwe"
"date":"16-2-2022"
}
{
"name":"qpe"
"date":"16-2-2022"
}
]
}
You can get the object keys with Object.keys function.
const keys = Object.keys(myMap);
const first = keys[0];
const last = keys[keys.length-1];

How to check nested JSON property and value exist in JavaScript?

I am getting below JSON as API response. Response contains multiple session node, each session node contains multiple event node. I would like to identify the first "SEARCH" event ("type") in any of the session ascending. If the "SEARCH" event is found, then, from the particular event, I need to get the "Interest" node value.
var guestJson = await response.json();
for(var property in guestJson)
{
if(property === "sessions")
{
var sessionObj = JSON.parse(JSON.stringify(guestJson[property]))
for(var i=0; i< sessionObj.length; i++)
{
var eachSessionObj = JSON.parse(JSON.stringify(sessionObj[i]))
for(var sessionProperty in eachSessionObj)
{
if(sessionProperty === "events")
{
console.log("Events Found")
//console.log(sessionProperty)
}
}
}
}
}
I am able to do with for loop like below. But i think it's not the effective way of doing that
Below is the JSON structure
{
"firstName":"fn",
"lastName":"ln",
"gender":"male",
"sessions":[
{
"currency":"USD",
"events":[
{
"type":"SEARCH",
"status":"PROCESSED",
"arbitraryData":{
"interest":"Health"
}
},
{
"type":"CHECK",
"status":"PROCESSED",
"arbitraryData":{
"interest":"Dental"
}
}
]
},
{
"currency":"USD",
"events":[
{
"type":"SEARCH",
"status":"PROCESSED",
"arbitraryData":{
"interest":"Health"
}
},
{
"type":"CHECK",
"status":"PROCESSED",
"arbitraryData":{
"interest":"Dental"
}
}
]
}
]
}
You could try a function like this:
function extractInterest(guestJson) {
// Get all sessions or else get an empty array
const sessions = guestJson.sessions || [];
// Filter all sessions with events
const interest = sessions.filter(session => session.events)
.flatMap(session => session.events) // Maps all the events to a single list
.filter(event => event.type === "SEARCH") // Filter only the events with type "SEARCH"
.map(event => event.arbitraryData.interest); // Extract the interest from each event
return interest; // return the list of interests
}
When applied to your example JSON, this returns an array of interests like this:
[ 'Health', 'Health' ]

How can i manipulate an object while inside of a loop

So i m trying to manipulate the object while going through the loop.
Well, its not working.. How can i make it work so the const patient has the property lastActivity inside of the this.model array?
javascript:
for (const item of data) {
const patient = this.model.find(
x => x.linkedUserId === item.userId
);
if (patient) {
patient.lastActivity = item.lastUploadDate;
}
}
The patient in the array itself is not updated, to make sure you are not updating a separate patient you can use a for-loop so that you definitely update the patient in the array.
for (const item of data) {
for (let i = 0; i < this.model.length; i++) {
if (this.model[i].linkedUserId === item.userId) {
this.model[i].lastActivity = item.lastUploadDate;
break;
}
}
}
If you can store data in this.model as an object you can update it easily. Consider the following model data.
{
"abcd": { linkedUserId: "abcd", name: "user1" },
"efgh": { linkedUserId: "efgh", name: "user2" },
}
Now you can update the model by doing the following.
for (const item of data) {
this.model[item.userId].lastActivity = item.lastUploadDate;
}
To get model in the form of an array you can do const model = Object.values(this.model);.

Nested Array Of JSON Looping in Typescript

I'm trying to get the value of "id" of the below mentioned array of json but i'm not able to get the result because it is surrounded by two "[[" array braces, can anybody please help me out, Also im getting these array of JSON from another loop if the loop runs single time i'm getting single array brace "[" , if the loop runs multiple times i'm gettin "[[" braces...
[
[
{
"attributes":{
"id":"Task_1yett21"
},
"incoming":"SequenceFlow_112bxv0",
"outgoing":"SequenceFlow_1gkdhq3"
},
{
"attributes":{
"id":"Task_0i5lteb"
},
"incoming":"SequenceFlow_1gkdhq3",
"outgoing":"SequenceFlow_1gjii2n"
},
{
"attributes":{
"id":"Task_1v37yfe"
},
"incoming":"SequenceFlow_1gjii2n",
"outgoing":"SequenceFlow_0bygyft"
}
]
]
I'm calling this function to get the JSON objects in the above array...
var getAllValuesOfKey = function (dataObj, queryKey) {
var resultArr = [];
if (!queryKey) {
return resultArr;
}
function execute(dataObj, queryKey) {
Object.keys(dataObj).forEach(function (key, index) {
if (typeof dataObj[key] == 'object' && !(dataObj[key] instanceof Array)) {
if (key == queryKey) {
resultArr.push(dataObj[key]);
}
execute(dataObj[key], queryKey);
} else if (key == queryKey) {
resultArr.push(dataObj[key]);
}
});
}
execute(dataObj, queryKey);
return resultArr;
}
var searchKey = 'task';
var result=getAllValuesOfKey(obj1, searchKey);
You can select the inner array in your loop with index 0 on the outer array, like this:
var myDoubleArray: any = [[{...}, {...}, {...}]];
for (let i = 0; i < myDoubleArray[0].length; i++) {
console.log(myDoubleArray[0][i].attributes.id);
}
If the arrays are still in JSON format, you need to first parse them to JavaScript before you can loop through the data. This can be done with JSON.parse().
var arr = [
[
{
"attributes":{
"id":"Task_1yett21"
},
"incoming":"SequenceFlow_112bxv0",
"outgoing":"SequenceFlow_1gkdhq3"
},
{
"attributes":{
"id":"Task_0i5lteb"
},
"incoming":"SequenceFlow_1gkdhq3",
"outgoing":"SequenceFlow_1gjii2n"
},
{
"attributes":{
"id":"Task_1v37yfe"
},
"incoming":"SequenceFlow_1gjii2n",
"outgoing":"SequenceFlow_0bygyft"
}
]
]
for (var i in arr[0]) {
//arr[0][i].attributes.id will give you the id
console.log(arr[0][i].attributes.id);
}

Check if object exists in another object

I have an object like this:
var obj = {
heroes: {
"1": {
label: "Spiderman"
},
"2": {
label: "Iron Man"
},
}
}
What I want to know it, whether there is an object e.g. 2 in obj.heroes.
I tried this, but it didn't work:
var name = "heroes"; //Will be a for-loop later
try {
if(name["2"] in obj)
console.log("There is an 2nd superhero!");
} catch(e) {console.log(e);}
..got only errors: "Cannot read property '2' of undefined"
I hope you are able to help me. Thanks
Try
if ("2" in obj[name]){
console.log("There is an 2nd superhero!");
}
But if you are trying to identify counts, it might be better if you used arrays
var obj = {
heroes: [
{label: "Spiderman"},
{label: "Iron Man"}
]
}
And check with
if (obj[name].length > 1) {
console.log("There is an 2nd superhero!");
}
You can do something like:
try {
console.log(obj.heroes["2"]);
} catch (e) {
console.log('nope :c');
}
However, it would be better to store heroes as an array:
var obj = {
heroes: [
{
label: 'Spiderman'
},
{
label: 'Ironman'
}
]
};
Using the array makes a little more sense since heroes consists of multiple hero objects.
If 2nd superhero doesn't exist the condition return false.
if(obj.heroes["2"])
console.log("There is an 2nd superhero!");
Or :
var count = 0;
for (var x in obj.heroes) {
if (obj.heroes.hasOwnProperty(x)) {
count++;
}
}
console.log("You see "+ count +" heroes.");
this code will hunt it down for you
var delve = function(object, property, dodge) {
if (!dodge) dodge = object;
for (var i in object) {
if (object[i] === dodge) continue;
if (typeof(object[i]) == typeof({})) this.delve(object[i], property, dodge)
if (i == property) console.log(object[i]);
}
}
delve(heroes,'2')

Categories

Resources