I have this array of objects. I have to create a new array with filtered results. I tried using the filter() method, but something doesn't go right, and the second array is empty.
Code for the original array:
#foreach (var item in list)
{
#:newsObj.push({
#:Id:#item.Id,
#:Title: "#item.Title",
#:FeaturedImage: "#item.FeaturedImage",
#:DateFormated: "#item.DateFormated",
#:Summary: "#item.Summary",
#:Category: "#foreach (var cat in #item.Category) {#(cat.Title+" ") } "});
}
And then code for filtering into the next one. Data filters based on the matching category:
newsObjFiltered = newsObj.filter(category => category.Category == selectedClass);
Related
I have a function that takes an array of RegEx(es) and applies them to the selected columns of an array of values, and returns this entire array of values with the columns transformed by the RegEx(es)
used like:
values = processRegEx(values, [0,4,7], RgX);
I want to generalize this so that if the array - colIdx has no entries, it runs on the entire array of values.
values = processRegEx(values, [], RgX);
I tried:
colIdx.length > 0 ? row[idx]=row[idx].replaceAll(...n) : row=row.replaceAll(...n);
but this does not work as no RegEx gets applied. the original array values is returned
How do to do this?
What I have so far:
// Add more as needed:
// [Regex, Replacement]
const RgX = [
[/\bN\./g, 'North'],
[/\bS\./g, 'South'],
[/\bSt\./g, 'Street']
];
function processRegEx(arr, colIdx, replaceTable) {
arr.forEach(function(row){
colIdx.forEach(function(idx){
replaceTable.forEach(function(n){
row[idx]=row[idx].replaceAll(...n)
});
});
});
return arr;
};
I am trying to find a way to build my custom array, but I am not able to do so.
What I have done so far:
I have my array constructed like so:
const super_array = [];
super_array.push({
produs: rezultate[i].produs,
email: rezultate[i].email,
pretDorit: rezultate[i].pretDorit
});
Further down into the code, I want to assign new data to the array, like so :
for(let j=0; j<results.length; j++) {
priceNumber = parseFloat(results[j].replace('<span>Lei</span>', '')) ;
super_array.push({price: priceNumber})
}
Result:
Right now, I get the following structure:
super_array({
produs: rezultate[i].produs,
email: rezultate[i].email,
pretDorit: rezultate[i].pretDorit
}, {pret: priceNumber});
What I would like to get is:
super_array({
produs: rezultate[i].produs,
email: rezultate[i].email,
pretDorit: rezultate[i].pretDorit,
pret: priceNumber
});
I am not sure if I have explained it correctly. Basically I want to have the priceNumber uniquely match with the other data in the existing array, and not to be added as a separate index.
super_array[0].pret = priceNumber
super_array.push adds a new object to the array. What you are trying to do in the last code is adding a property to an object of the array.
For example: super_array[0].pret = priceNumber will add the property pret with the value of priceNumber. Here I'm not adding new objects to the array.
I am new in coding JavaScript. So far I know how to set and get values from a multi array, but with this one I cannot find the right way to do it.
I am trying to get the email value from this array:
__arr.push(['id' ,'12541']);
__arr.push(['tag', {"sub":false,"email":"email#email.com"}]);
I tried
JSON.parse(__ar.tag.email)
document.write(__ar[2][2])
Everything I tried so far I got either undefined or tag[object, object].
What's the easiest way to get it?
The email property is located on the second element of the array (that is index 1 of the zero based indexed array). So, to access it, you also need to access the second object of the element (again index 1) and then .email is at your hand:
document.write(__arr[1][1].email);
Assuming that you only push those two values, your array looks like the following:
[
['id' ,'12541'],
['tag', {"sub":false,"email":"email#email.com"}]
]
Means, that when you access it using __arr.tag.email will result in an undefined error, because it's an array not an object.
Therefore what you could do is, if you don't know exactly the index:
var __arr = [];
__arr.push(['id' ,'12541']);
__arr.push(['tag', {"sub":false,"email":"email#email.com"}]);
for (var i = 0; i < __arr.length; i++){
if(__arr[i][0] === 'tag'){
console.log(__arr[i][1].email);
break;
}
}
so you have an array as __arr, the first element you are pushing is id which is an array second array is having your email id.
so you can access as shown below.
I hope this will solve your issue
var __arr = [];
__arr.push(['id' ,'12541']);
__arr.push(['tag', {"sub":false,"email":"email#email.com"}]);
console.log("email id =>", __arr[1][1].email)
I hope you know array is starting from its index that's base value is 0. in your code there is no such element which is available in index 2.
document.write(__ar[2][2]) //
I know lots of answer is given here, but i just want to tell you even you are pushing value in "__arr" i.e an array of array. so every element is storing in its index value.
var __arr = [];
__arr.push(['id' ,'12541']);
__arr.push(['tag', {"sub":false,"email":"email#email.com"}]);
console.log(__arr[0]) //return you ["id", "12541"]
console.log(__arr[1]) //return you ["tag", {sub: false, email: "email#email.com"}]
again you can see inside of your "__arr" there is a an array element
console.log(__arr[0][0]) //return you "id"
console.log(__arr[0][1]) //return you "12541"
console.log(__arr[1][0]) //return you "tag"
console.log(__arr[1][1]) //return you {sub: false, email: "email#email.com"}
and here what you want i.e.
console.log(__arr[1][1].sub) //return you false
console.log(__arr[1][1].email) //return you "email#email.com"
A dynamic way to do it (with level of 2 nested levels).
Basically, I used two nested loops and aggregated the emails into a list.
let __arr = []
__arr.push(['id' ,'12541']);
__arr.push(['tag', {"sub":false,"email":"email#email.com"}]);
__arr.push(['tag2', {"sub":false,"email":"2222#email.com"}]);
const emails = __arr.reduce((res, items) => {
items.forEach(elem => {
if (elem.email) res.push(elem.email)
})
return res
},[])
console.log(emails)
// [ 'email#email.com', '2222#email.com' ]
I have a JavaScript Array of Objects, on a button click I push an object into the array and then use that as a datasource for a grid. The issue I am facing is that initially the first object in the array is all blank values and when I load the grid I have a blank row because of the empty object... How do I remove that empty object from the array before I load the grid?
Here is the array
var gridData = {
step3GridData: [{ Description: "", Color: "", SqSiding: "" }]
};
and on a button click I am pushing a new object to the array
gridData.step3GridData.push({ Description: $("#InfoInsul").text(), Color: $("#ddGetInsulationMaterialColor").val(), SqSiding: $("#ddInsulationSquares").val() });
LoadStep3(gridData.step3GridData);
As mentioned, I need to remove that empty object before I bind the load with the array. How would I go about doing this?
Use splice. If you are certain it is always the first item in the array, you can do:
if (gridData.length && Object.keys(gridData[0]).length === 0) {
gridData.splice(0, 1);
}
If you are not certain about its position, you can traverse the array and remove the first empty object:
for (const [idx, obj] of gridData.entries()) {
if (Object.keys(obj).length) === 0) {
gridData.splice(idx, 1);
break;
}
}
First, initialize your array like this:
var gridData = {
step3GridData: [] // empty array
};
Then when you are pushing a new object, check if the inputs are filled like this:
var desc = $("#InfoInsul").text(); // this seems unnecessary as this is not left to the user to fill (if I'm assuming right then don't check if this is empty)
var col = $("#ddGetInsulationMaterialColor").val();
var sqs = $("#ddInsulationSquares").val();
if(desc.length && col.length && sqs.length) { // if desc is not empty and col is not empty and sqs not empty then add an object
gridData.step3GridData.push({ Description: desc, Color: col, SqSiding: });
}
Now if the user left something empty, the object won't get pushed, thus there will be no empty objects. You can make use of else to alert a message saying that the user left some input blank.
I am using mongodb and am building an application with two collections: users and items.
I'd like for users to be able to save items that they like and go to their saved items page where the items would be displayed in the reverse order that they were saved (last saved appears first).
At the moment, I am adding every saved item's id along with the savedDate to the user's profile savedItems array like so:
user profile
{
savedItems: [{id: "", savedDate: ""}, {id: "", savedDate: ""}, etc...]
}
Whenever I need to retrieve those items, I query the items collection for objects with ids $in this array. Like this:
var items = Items.find({_id: {$in: _.pluck(user.savedItems, 'id')}});
The problem here is that I can't order those items according to the addedDate.
So is it possible to map the addedDate onto every object of the retrieved items?
(Something like: if retrievedItems.id == savedItems.id, then push the addedDate there.)
Which would result in an items array like this:
[
{id:"", itemName:"", price: "", [...], savedDate: ""},
{id:"", itemName:"", price: "", [...], savedDate: ""},
[...]
]
Thank you.
JSFIDDLE
I created two function to help you do it:
function mergeDates(listDates, listItems) {
for (var i = 0; i < listDates.length; i++) {
var index = findListIndex(listItems, listDates[i].id);
if (index != null) listItems[index].savedDate = listDates[i].savedDate;
}
return listItems;
}
function findListIndex(listItems, id) {
for (var i = 0; i < listItems.length; i++) {
if (listItems[i].id == id) return i;
}
return null;
}
The first one, mergeDates, takes your first list wich contains the date, the second list, listItems, is the list of your items.
I loop the list with dates, and for each items in it, i call a second function that return the index of the same element in the second list, so findListIndex will search all element and return it's index when he find the same id.
Now the function mergeDates, with the newly found index, will add the value savedDate to your listItems and make it equals to the one on the listDates !
Then the function return the list with all the info of the items, including the dates!
Here is how to call the function:
var listWithDate = mergeDates(savedItems, items);
Hope it helps !