trying to loop through the array of objects and find the match - javascript

i have below object structure like as in below image and i am trying to match with the inner object property(like massing type id) with the existing ID and if it is match i need to get the name of that object and push it to array and set that array in state object,
and the code is looks like as below
Object.values(constructionSets).forEach(item => {
console.log(item);
const constructionSetItem = [];
if (
item.ashraeClimateZone?.id === ashraeClimateZoneId &&
item.massingType?.id === massingTypeId &&
item.sourceOfData?.id === energyCodeId
) {
setConstruction(constructionSetItem.push(item.name));
}
});
and when i log item i am getting array of objects instead of single object, could any one please let me know where i am doing wrong with the above code?
thanks in advance.

From what I see in the information you gave, that constructionSets variable is already an Array so to loop it, you just need to do:
constructionSets.forEach(item => {...})

Related

Use a filter in typescript array to get a value of the first node returned

I have an array coming in that can be filtered but sometimes it will return no results after the filter and other times 1 result, which is the one I need.
It goes something like this:
this.outArray.variableTest = inArray.info.filter(q => (q.myId=== TestIdTypes.FirstId)[0].name;
The problem is that the filter can be undefined if nothing is matched, causing an exception. If something matches then [0].name is correct and what I want. How do I check if it has length 0 or undefined? I can use any other typescript code if needed.
You can use Array.prototype.find instead of filter and use the optional chaining operator.
const name = inArray.info.find(q => q.myId=== TestIdTypes.FirstId)?.name;
Just check if the resulting item is defined or not first:
const filtered = inArray.info.filter(q => q.myId=== TestIdTypes.FirstId);
if (filtered.length) {
this.outArray.variableTest = filtered[0].name;
}
But .find would really be more appropriate (and a bit more type-safe):
const found = inArray.info.find(q => q.myId === TestIdTypes.FirstId);
if (found) {
this.outArray.variableTest = found.name;
}

How to calculate the number of objects I get from the loop Javascript

I filtered my set of users(array) with if(elem.id_verified). I now get 77 users objecta. I just want to take the number of these objects. I tried with console.log(this.numOfunverifiedUsers.length) but i get 77 underfined. My question is how to assemble all objects and get that number. Maybe my logic is going in the wrong direction.
this.users=response.data.users
this.numOfunverifiedUsers = []
this.users.forEach(elem => {
if (elem.id_verified === 0) {
this.numOfunverifiedUsers = elem
console.log(this.numOfunverifiedUsers.length)
}
})
this.numOfunverifiedUsers.push(elem)
Push the element in array.
this.numOfunverifiedUsers = elem , replace it with above
This should work too:
console.log(this.users.filter(function (val) {
return val.id_verified === 0
}).length)
filter items that are id_verified === 0 and count their length.
I think would be better you build that list with a filter:
this.numOfunverifiedUsers = this.users.filter(
user => user.id_verified === 0
);
console.log(this.numOfunverifiedUsers);
console.log(this.numOfunverifiedUsers.length);
If you want to read about filter: Filter method
With this.numOfunverifiedUsers = elem, you are assigning 'elem' to an array reference. As a result, you get exceptions which make the '=' operator return the undefined primitive type (as the result of function errors; see undefined - JavaScript | MDN). What you want to do is either add the element iteratively into the array the "old way", via element assigning, or just use the OOP way via the push method. The former wouldn't require a count function, as you can do something like that:
var count = 0; //outside the forEach
...
if (elem.id_verified === 0) {
{
this.numOfunverifiedUsers[count++]=elem
console.log(count)
}
...
However, as others pointed out, using a filter makes the code much more clean and readable
This would work better with the use of a Filter
console.log(this.users.filter(function (val) {
return val.id_verified === 0
}).length)
filter items that are id_verified === 0 and count their length.

replace object in array base on index

So, Im using react and I need to keep adding objects to an array of objects (object may have the same index, thats why I check for label and index). When the object that I want to add has the same label property as one that already is in that array, it should replace the previous object. So, lets say, only one object for each label. What I have works until I work with more then one label. When I do so, the array accepts more than one objects for each label...
if (this.state.thumbnailsAtivas.some(thumbnail => {
thumbnail.index === textura.index
}) && this.state.thumbnailsAtivas.some(thumbnail => {
thumbnail.label === textura.label
})) {
console.log("already in array");
}
else if (this.state.thumbnailsAtivas.some(thumbnail => thumbnail.label === textura.label)) {
console.log("label already with item");
this.state.thumbnailsAtivas.some((thumbnail, index) => {
const tempData = (this.state.thumbnailsAtivas).slice(0);
tempData[index] = textura;
this.setState({thumbnailsAtivas: tempData})
})
} else {
this.setState({thumbnailsAtivas: [...this.state.thumbnailsAtivas, textura]},);
}
You can use another Array function called findIndex which have the same usage as some but returns a result like indexOf does (returns the index of the element in an array or -1 if no element matches):
let index = this.state.thumbnailsAtivas.findIndex(
thumbnail => thumbnail.label === textura.label
);
if(index !== -1) {
this.state.thumbnailsAtivas[index] = yourNewObject;
}
Note: To optimise your code a little bit, you could get rid of the call to some and use findIndex (once) for both checking existence and finding the index.

Rendering a single element from an array of data in React

If I was to map through an array of objects of data and only wanted to render a single element from the array based on a certain condition like below:
dataArray.map((element, i) => {
if(i === currentElement){
return (
<div>{element.data}</div>
)
} else {
return null;
}
});
Would that be acceptable? this seems to return what I am after but was curious if this was the most efficient way to go about it because this still returns an array with a length of the data array with all null elements except on the desired single element.
Using map on an array will return another array with your function performed on each element, so the function you are using is literally pushing the value 'null' into the return array for any element that doesn't pass your condition. You could just use
dataArray.map((ele, i) => {
if(i === currentElement){
return (
<div>{element.data}</div>
)
}
and the map will simply do nothing with any element that does not pass the condition.
Mapping over an array in React is usually (often?) used for creating <li> tags, and React might get cranky in your console about not having a key. If you see that, check out this link here: https://reactjs.org/docs/lists-and-keys.html
You could use the find function to get the value you want to render rather than rendering a bunch of null values.
const element = dataArray.find((el, i) => i === currentElement);
if(element) {
return (<div>{element.data}</div>);
}

Check if item from one object exists in another (using underscore)

I am trying to compare 2 objets using underscore, specifically I am trying to compare the key/values of "id" (because other things inside will change). I basically want to just check if object A has an item that object B does not have, remove it from object A. Here is my attempt at it :
for(var c=0;c<$scope.types.length;c++){
var real = _.some($scope.storeTempName, function(it) {
return it.id == $scope.types[c].typeId;
});
if(real){
}else{
$scope.types.splice(c,1);
}
}
Where $scope.storeTempName is object B and $scope.types is object A. So if $scope.types has something $scope.storeTempName does not, remove it (tracking by id and typyId for types).
This first attempt I have works, BUT it only will remove the first one. My guess is it's becasue I'm looping from 0 ++ and the index's are changing when i remove the first one so splice is targetting a false item. I am not sure though, and could use some help. Thank you for reading!
Just use _.filter.
$scope.types = _.filter($scope.types, function (type) {
return _.some($scope.storeTempName, function (it) { return it.id == type.typeId })
})

Categories

Resources