I have an array,
data =[{"date":"12/1/12","value":21},
{"date":"12/2/12","value":34},
{"date":"12/1/12","value":36},
{"date":"12/1/12","value":32},
{"date":"12/2/12","value":1},
{"date":"12/2/12","value":4},
{"date":"12/2/12","value":3},]
i need to create another array like by retrieving values from the arrays,
data1=[{"date":"12/1/12","value":21},
{"date":"12/1/12","value":36},
{"date":"12/1/12","value":32}]
data2 =[{"date":"12/2/12","value":3},
{"date":"12/2/12","value":4},
{"date":"12/2/12","value":1},
{"date":"12/2/12","value":34}]
const data1 = data.filter(datum => datum.date === ‘12/1/12’)
const data2 = data.filter(datum => datum.date === ‘12/2/12’)
Related
Let say I have dynamic array
const branddata = ["adidas", "nike", "puma"]
//this data can be sometime empty too like
// const branddata = []
//now I want to search all the product with brands like
const product = productmodel.find({brand:branddata})
The problem is, this thing works when branddata array is not empty and it gives me the product.
But when it is empty the find method search for a brand which is equal to "" and gives me zero product.
I want all the products to be displayed if branddata is empty.
How can I get this using $regex or any other?
you can check branddata is empty or not, and create query object based on it, like this
let q=(branddata && branddata.length>0 )?{brand:branddata}:{};
const product = productmodel.find(q);
when you have multiple params,you can do something like this
let params={
"brand":branddata,
"price":pricedata,
"gender":genderdata
}
let q={};
Object.Keys(params).forEach((t)=>{
if(params[t] && params[t].length>0 ){
q[t]=params[t]
}
})
const product = productmodel.find(q);
Finally found a solution with a function-based approach
$in is used to find document data which are in the array and $nin is used to find document data which are not in the array (basically when array is empty)
const branddata = ["adidas", "nike", "puma"]
const pricedata =["100"]
const genderdata =["male","female"]
const queryfunc = (value)=>{
var q = {}
if(value==''){
q["$nin"]=value;
}
else{
q["$in"]=key;
}
return q
}
const brand=queryfunc(branddata)
const price=queryfunc(pricedata)
const gender=queryfunc(genderdata)
const product = productmodel.find({brand,price,gender})
I'm trying to reorder the items in an object so they will match the order of an array. The object is the row data and the array is the column names.
Here are the order of column names I want to match:
columnNames [
"System.Id",
"System.WorkItemType",
"System.Title",
"System.AssignedTo",
"System.State",
"Microsoft.VSTS.Common.ActivatedDate",
"System.ChangedDate",
"Microsoft.VSTS.Common.ClosedDate"
]
Here is an example of the object items I'm trying to reorder:
fields = {"System.Id":7993,"System.WorkItemType":"Task","System.State":"Closed","System.AssignedTo":"Jack Smith","System.ChangedDate":"2022-07-19T12:14:25.193Z","System.Title":"Update Dev Environment","Microsoft.VSTS.Common.ActivatedDate":"2022-07-19T12:13:49.713Z","Microsoft.VSTS.Common.ClosedDate":"2022-07-19T12:14:25.193Z"}
Ultimately I just want the values of each item in the object placed in an array which matches the order of the columnNames array, so like this:
rowArray = [
7993,"Task","Update Dev Environment","Jack Smith","Closed","2022-07-19T12:14:25.193Z","2022-07-19T12:13:49.713Z","2022-07-19T12:14:25.193Z"]
I get the fields object from calling an API. In order to get only the fields I want I loop through part of the API response.
Here's my entire code if it helps to see what I'm trying to do:
queryItems = result from API call
queryItems.forEach((item) => {
let sortingfields = [];
let sortedfields = [];
let rowArray = [];
//loop through fields part of each response item and add it to new array sortingfields
Object.entries(item.fields).forEach(([key, value]) => {
switch(key){
case 'System.AssignedTo':
sortingfields.push(key, item.fields[key].displayName);
break;
case 'System.ChangedDate':
const changedDate = item.fields[key].toLocaleString(DateTime.DATETIME_FULL);
sortingfields.push(key, changedDate);
break;
case 'Microsoft.VSTS.Common.ActivatedDate':
const activatedDate = item.fields[key].toLocaleString(DateTime.DATETIME_FULL);
sortingfields.push(key, activatedDate);
break;
case 'Microsoft.VSTS.Common.ClosedDate':
const closedDate = item.fields[key].toLocaleString(DateTime.DATETIME_FULL);
sortingfields.push(key, closedDate);
break;
default:
sortingfields.push(key, item.fields[key]);
break;
}
})
// sort array items so they match the order of the columnNames array
sortedfields = sortingfields.sort((entryA, entryB) => {
const [keyA] = entryA;
const [keyB] = entryB;
return columnNames.indexOf(keyA) - columnNames.indexOf(keyB)
})
// loop through sorted array and retrieve only the values
for (let s of sortedfields){
rowArray.push(sortedfields[s]);
}
// add array as a new row to Excel file using ExcelJS
let row = sheet.addRow(rowArray);
})
Now the error I get is Failure Exception: entryA is not iterable. I don't understand why given sortingfields is an array.
you can use map for that
you just map over the keys you want and get it from the object like this
const orderData = (data, order) => order.map(k => data[k])
const columnNames = [
"System.Id",
"System.WorkItemType",
"System.Title",
"System.AssignedTo",
"System.State",
"Microsoft.VSTS.Common.ActivatedDate",
"System.ChangedDate",
"Microsoft.VSTS.Common.ClosedDate"
]
const single = {"System.Id":7993,"System.WorkItemType":"Task","System.State":"Closed","System.AssignedTo":"Jack Smith","System.ChangedDate":"2022-07-19T12:14:25.193Z","System.Title":"Update Dev Environment","Microsoft.VSTS.Common.ActivatedDate":"2022-07-19T12:13:49.713Z","Microsoft.VSTS.Common.ClosedDate":"2022-07-19T12:14:25.193Z"}
const data = [{"System.Id":7993,"System.WorkItemType":"Task","System.State":"Closed","System.AssignedTo":"Jack Smith","System.ChangedDate":"2022-07-19T12:14:25.193Z","System.Title":"Update Dev Environment","Microsoft.VSTS.Common.ActivatedDate":"2022-07-19T12:13:49.713Z","Microsoft.VSTS.Common.ClosedDate":"2022-07-19T12:14:25.193Z"}, {"System.Id":7993,"System.WorkItemType":"Task","System.State":"Closed","System.AssignedTo":"Jack Smith","System.ChangedDate":"2022-07-19T12:14:25.193Z","System.Title":"Update Dev Environment","Microsoft.VSTS.Common.ActivatedDate":"2022-07-19T12:13:49.713Z","Microsoft.VSTS.Common.ClosedDate":"2022-07-19T12:14:25.193Z"}]
console.log(orderData(single, columnNames))
console.log(data.map(d => orderData(d, columnNames)))
I'm not really sure of what you want to achieve but here is my answer:
const fieldEntries = Object.entries(fields);
const entriesResult = fieldEntries.sort((entryA, entryB) => {
const [keyA] = entryA;
const [keyB] = entryB;
return columnNames.indexOf(keyA) - columnNames.indexOf(keyB)
})
const objResult = Object.fromEntries(entriesResult)
This gives the following value for objResult:
{
System.Id:7993
System.WorkItemType:"Task"
System.Title:"Update Dev Environment"
System.AssignedTo:"Jack Smith"
System.State:"Closed"
Microsoft.VSTS.Common.ActivatedDate:"2022-07-19T12:13:49.713Z"
System.ChangedDate:"2022-07-19T12:14:25.193Z"
Microsoft.VSTS.Common.ClosedDate:"2022-07-19T12:14:25.193Z"
}
Sandbox: https://playcode.io/932608
I have this function that required selected Ids into an array and the result is this
[7950, 7949, 7948, 7947, 7945, 7944, 7943, 7942, 7941, 7938]
But now I want to results to be formatted like [{id: 7950}, {id:7949}] etc
function
this.checked = this.students.filter((student) => student.checked === true).map((student) => student.id);
Simply return an object in your map function.
const arr = [7950, 7949, 7948, 7947, 7945, 7944, 7943, 7942, 7941, 7938].map(id => ({id}));
console.log (arr);
You could map objects with a short hand property.
var ids = [7950, 7949, 7948, 7947, 7945, 7944, 7943, 7942, 7941, 7938],
result = ids.map(id => ({ id }));
console.log(result);
I am new to typescript .please help me in doing this.
I have an array as below.
let pets=[{id:"1",name:"animal"},{id:"2",name:"animal"}];
i want to loop through pets and get the names of animals from another array Category where
let category = [{id:"1",name:"Dog"},{id:"2",name:"Cats"},{id:"3",name:"Cows"},{id:"4",name:"Goat"}]
get output as below,
// expected output,
newpets=[{id:"1",name:"Dog"},{id:"2",name:"Cats"}]
Try this out. I have used, Array map() and Array find() to achieve this.
let pets=[{id:"1",name:"animal"},{id:"2",name:"animal"}];
let category = [{id:"1",name:"Dog"},{id:"2",name:"Cats"},{id:"3",name:"Cows"},{id:"4",name:"Goat"}]
let newPets = pets.map(eachPet => {
return category.find(eachCat => eachPet.id === eachCat.id)
})
console.log(newPets)
There can be many ways to do it. One way
let pets=[{id:"1",name:"animal"},{id:"2",name:"animal"}];
let Category = [{id:"1",name:"Dog"},{id:"2",name:"Cats"},{id:"3",name:"Cows"},
{id:"4",name:"Goat"}];
var newpets = [];
pets.forEach(pet => {
let animalType = Category.find(cate => pet.id === cate.id );
newpets.push({id:pet.id, name: animalType.name});
})
console.log(newpets);
My data is in the following format..
var data= [['typeName', 'valueName'], ['type1', 'value1'],
['type1', 'value2'],['type2', 'value3'],['type2', 'value4']]
I wish to transform the above data to data as below..
var resultdata=[{'typeName':'type1','valueName':['value1','value2']},
{'typeName':'type2','valueName':['value3','value4']}]
Basically I pick up distinct 'typeName' values and then group 'valueName' values by 'typeName' values.
I would preferably use only knockoutjs, lodash or underscorejs as my soln already uses them but I'm open to other solutions as well..
All help is sincerely appreciated
Thanks
I think this solution using underscore should do the trick:
var result= _.chain(data)
.rest()
.groupBy( value => value[0])
.map( (value,key) => ({ [data[0][0]]: key, [data[0][1]]: _.map(value, val => val[1])}))
.value();
This solution uses rest to skip the first item in the data array (the type descriptors). The array is then grouped by the first value in the array (the type) and the mapping returns the grouping in the required form using es6 object initializer notation.
Given the result as:
var resultdata=[
{'typeName':'type1'},{'valueName':['value1','value2']},
{'typeName':'type2'},{'valueName':['value3','value4']}
]
I'm going to call 'typeName' the category and 'valueName' the items.
Since the original data look like this:
var data= [
['typeName', 'valueName'],
['type1', 'value1'],
['type1', 'value2'],
['type2', 'value3'],
['type2', 'value4']
]
It is clear there is a pattern. The first row of data is what we'll use as labels for category and items. All the remaining data represent the values being used inside category and items.
The first step is to extract the labels:
var categoryLabel = data[0][0];
var itemLabel = data[0][1];
Next, the unique categories will need to be determined, so we'll use reduce to build an array of unique categories:
var categories = data
.filter(function(row, i) { return i > 0 }) // remove the labels
.reduce(function(arrCategories, currRow) {
// Add the current rows' category if it doesn't already exist
var currCategory = currRow[0];
if (arrCategories.indexOf(currCategory) === -1) {
return arrCategories.concat(currCategory);
}
return arrCategories;
}, [])
Now that you have a set of categories, you just need to iterate over each one to find all items that belong to it:
var valuesByCategory = {};
categories.forEach(function(category) {
// find all the data items that match the category
var items = data
.filter(function(row) { return row[0] === category; })
.reduce(function(arrItems, currRow) {
var currItem = currRow[1];
if (arrItems.indexOf(currItem) === -1) {
return arrItems.concat(currItem);
}
return arrItems;
}, []);
valuesByCategory[category] = items;
});
Now that all the data has been parsed out, the only thing left to do is build the resultant array:
var resultdata = [];
// iterate through each of the categories
categories.forEach(function(category) {
// using the category label, output an object with the label and category
var categoryObj = {};
categoryObj[categoryLabel] = category;
resultdata.push(categoryObj);
// Next, create a items object containing all the values
var itemsObj = {};
itemsObj[itemLabel] = valuesByCategory[category];
resultdata.push(itemsObj);
}
and that's it :)
The best part is that you don't need any external libraries. This is all ES2015 javascript!
Here is a lodash version of Gruff Bunnies solution:
var data= [['typeName', 'valueName'], ['type1', 'value1'], ['type1', 'value2'],['type2', 'value3'],['type2', 'value4']]
var names = data[0]
var values = _.tail(data)
console.log(JSON.stringify(
_(values)
.groupBy(0)
.map( (value, key) => ({ [names[0]]: key, [names[1]]: _.map(value, 1)}) )
.value()
))
https://jsfiddle.net/nmf1fdf5/