give property name to values in an array - javascript

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);

Related

looking to sort items in object to match order of array

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

How to loop through an array and get the name corresponding to id and assign the result to another array

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);

how to get same date as one array

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’)

Dynamically create array of objects, from array of objects, sorted by an object property

I'm trying to match and group objects, based on a property on each object, and put them in their own array that I can use to sort later for some selection criteria. The sort method isn't an option for me, because I need to sort for 4 different values of the property.
How can I dynamically create separate arrays for the objects who have a matching property?
For example, I can do this if I know that the form.RatingNumber will be 1, 2, 3, or 4:
var ratingNumOne = [],
ratingNumTwo,
ratingNumThree,
ratingNumFour;
forms.forEach(function(form) {
if (form.RatingNumber === 1){
ratingNumOne.push(form);
} else if (form.RatingNumber === 2){
ratingNumTwo.push(form)
} //and so on...
});
The problem is that the form.RatingNumber property could be any number, so hard-coding 1,2,3,4 will not work.
How can I group the forms dynamically, by each RatingNumber?
try to use reduce function, something like this:
forms.reduce((result, form) => {
result[form.RatingNumber] = result[form.RatingNumber] || []
result[form.RatingNumber].push(form)
}
,{})
the result would be object, with each of the keys is the rating number and the values is the forms with this rating number.
that would be dynamic for any count of rating number
You could use an object and take form.RatingNumber as key.
If you have zero based values without gaps, you could use an array instead of an object.
var ratingNumOne = [],
ratingNumTwo = [],
ratingNumThree = [],
ratingNumFour = [],
ratings = { 1: ratingNumOne, 2: ratingNumTwo, 3: ratingNumThree, 4: ratingNumFour };
// usage
ratings[form.RatingNumber].push(form);
try this its a work arround:
forms.forEach(form => {
if (!window['ratingNumber' + form.RatingNumber]) window['ratingNumber' + form.RatingNumber] = [];
window['ratingNumber' + form.RatingNumber].push(form);
});
this will create the variables automaticly. In the end it will look like this:
ratingNumber1 = [form, form, form];
ratingNumber2 = [form, form];
ratingNumber100 = [form];
but to notice ratingNumber3 (for example) could also be undefined.
Just to have it said, your solution makes no sense but this version works at least.
It does not matter what numbers you are getting with RatingNumber, just use it as index. The result will be an object with the RatingNumber as indexes and an array of object that have that RatingNumber as value.
//example input
var forms = [{RatingNumber:5 }, {RatingNumber:6}, {RatingNumber:78}, {RatingNumber:6}];
var results = {};
$.each(forms, function(i, form){
if(!results[form.RatingNumber])
results[form.RatingNumber]=[];
results[form.RatingNumber].push(form);
});
console.log(results);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
HIH
// Example input data
let forms = [{RatingNumber: 1}, {RatingNumber: 4}, {RatingNumber: 2}, {RatingNumber: 1}],
result = [];
forms.forEach(form => {
result[form.RatingNumber]
? result[form.RatingNumber].push(form)
: result[form.RatingNumber] = [form];
});
// Now `result` have all information. Next can do something else..
let getResult = index => {
let res = result[index] || [];
// Write your code here. For example VVVVV
console.log(`Rating ${index}: ${res.length} count`)
console.log(res)
}
getResult(1)
getResult(2)
getResult(3)
getResult(4)
Try to create an object with the "RatingNumber" as property:
rating = {};
forms.forEach(function(form) {
if( !rating[form.RatingNumber] ){
rating[form.RatingNumber] = []
}
rating[form.RatingNumber].push( form )
})

getting distinct values from array of arrays in Javascript

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/

Categories