I am getting the IDs from an array when I select a few rows (a lot of data is coming in and I only need the IDs). I want that when obtaining the IDs an array is created for me ONLY with the IDs. The problem is that when I try I get the following (by console):
Id Seleccionado: 78
Id Seleccionado: 79
Id Seleccionado: 81
And I would like to obtain them as a normal array:
{ 78, 79, 81 }
TS
procesarClic() {
const request = this.selection.selected;
for (let i = 0; i < request.length; i++){
const list = request[i].id;
console.log('Id Seleccionado: ', list);
}
}
The request constant it is where the selected rows are with all the data in the array, since many rows can be selected.
Thank you for your contribution and help!
You have to create the array and filling it up like this:
procesarClic() {
const request = this.selection.selected;
let array = [];
for (let i = 0; i < request.length; i++){
const list = request[i].id;
console.log('Id Seleccionado: ', list);
array.push(request[i].id);
}
}
This way, you will have an array with only ids in it.
BR
Assuming this.selection.selected is an array which it seems to be, you could use the map function, ie.
const examples = [
{id: 1, name: "One"},
{id: 2, name: "Two"},
{id: 3, name: "Three"}
]
const onlyIds = examples.map(e => e.id);
console.log(onlyIds);
which would return an array consisting of ids only.
Related
I am currently struggling with this problem. Hopefully, you can help me :)
Data is selected from a Database and it returns Objects structured like this:
object = {
id: 4,
name: "Banana",
idParent: 1
}
idParent would be the section of the product.
There are a lot of products and a lot of sections so a simple
const sectionOne = [];
ObjectList.map(e => {
if(e.idParent === 1) {
sectionOne.push(e);
}
})
would probably be wrong, because it should be possible to add other idParents in the future and code should not need some rework in that case.
Let's say there are 30 Objects, 10 have idParent = 1, 15 have idParent = 2 and the last 5 have idParent = 3.
How can the whole list be divided into these sections without making a variable for each section?
Thanks for the help :)
What I believe you need here is a map which groups the values of the list by idParent.
Example:
const objectList = [{
id: 4,
name: "Banana",
idParent: 1
},
{
id: 3,
name: "apple",
idParent: 2
},
{
id: 5,
name: "orange",
idParent: 2
}];
const groupBy = (array, key) => {
return array.reduce((accumlator, value) => {
(accumlator[value[key]] = accumlator[value[key]] || []).push(value);
return accumlator;
}, new Map());
};
const resultMap = groupBy(objectList, "idParent");
console.log(resultMap);
enter code here
The sub-arrays from the map can be access also like this:
const groupWihtIdParen1 = resultMap[1];
// or like this
const groupWithIdParent2 = resultMap.get(2);
``
I have two arrays one with field names and the other array is having a list of arrays where each array corresponds to row in table.How can i use these two arrays to create a list of JSON Objects. Is there any in built function. I am able to acheive this using map/reduce/ for -loop but this is impacting the performance if the second array is having more rows as we have traverse through each row.
I hope the following explains the use case better. Please share the sample code if possible.
Arr1=[field1,field2];
Arr2=[[1,2],[3,4],[5,6]];
Expected Output:
[
{
field1 :1 ,
field2: 2
},
{
field1 :3 ,
field2: 4
},
{
field1 :5 ,
field2: 6
}
]
You can use Array.map to map the elements
const mapFields = (arr1, arr2) => {
const mappedArray = arr2.map((el) => {
const mappedArrayEl = [];
el.forEach((value, i) => {
if (arr1.length < (i+1)) return;
mappedArrayEl[arr1[i]] = value;
});
return mappedArrayEl;
});
return mappedArray;
}
const Arr1 = ["field1","field2"];
const Arr2 = [[1,2],[3,4],[5,6]];
console.log(mapFields(Arr1, Arr2));
I have the following JSON definition:
export class Company {
name: string;
trips : Trip[] = [];
}
I am able to see the trips in the console using:
console.log(this.company);
But I am not able to access the array elements (trip), I've tried
the following:
for(let i = 0; i < this.company.trips.length; i++){
console.log(this.company.trips[i]);
}
When I display the company to the log I'm getting the trip as you can
see below:
{id: 1}
name: "Sample"
trips: {id: 1, r: "ABC"}
id: 1
Any idea how to access array elements in Angular thanks?
Using a combination of Object.keys() and forEach() will let you iterate through the the object in a similar fashion to an array.
explination
const x = {hello: "hi"};
console.log(Object.keys(x)); // will return array looking like
// [hello] which you can run a for each on.
Object.keys(x).forEach(data => {
console.log(x[data]); // will return `hi`
});
Solution
const trips = {id: 1, r: "ABC"}; // const trips = this.company.trips
if (trips) // check the value exists here
{
Object.keys(trips).forEach((data) => {
console.log(trips[data]);
});
}
if(this.company)
this.Company.trips.forEach(x => {
console.log(x);
});
Why that is not working in TypeScript?
Example:
views: any[] = [360001232825, 360001232845, 360001217389];
MyArray:any[];
for (var i = 0; i < this.views.length; i++) {
this.subscription = this.dataService.getMyData(this.views[i]).subscribe(data => {
this.myArray[this.views[i]]=data;
});
}
When I use .push data is inserted into my array but I want to use a specific index.
If you want to insert an Item use splice. But obviously you want to use a Map or an object.
let ar = ["one", "two", "four", "five"];
console.log("Before:\n" + ar);
ar.splice(2, 0, "three");
console.log("After:\n" + ar);
Maybe this will help:
let namedIndexes = [1564789, 234895, 249846];
let map = {};
let data = "this is your data arg";
namedIndexes.forEach((v, i, ar) => {
map[v] = data + " data at " + v;
});
console.log(map);
'map' is like your this.myArray, 'data' is your parameter and 'namedIndexes' is your view array. I hope the code explains itself.
I would like to merge two arrays with specific condition and update objects that they are containing.
First my struct that is in arrays:
struct Item {
var id:Int
var name:String
var value:Int
}
Second elements for the two arrays:
let fisrt = Item(id: 1, name: "Oleg", value: 3)
let second = Item(id: 2, name: "Olexander", value:5)
let fisrtInSecond = Item(id: 1, name: "Bogdan", value: 6)
let secondInSecond = Item(id: 2, name: "Max", value: 9)
Arrays:
var fisrtArray = [fisrt, second]
let secondArray = [fisrtInSecond, secondInSecond]
I woudl like to use zip and map functions of the collection to achive result. Result is that fisrtArray elements names are updated by id.
Example: fisrtArray = [Item(id: 1, name: "Bogdan", value:3), Item(id: 2, name: "Max", value:5)]
I know how to do this via simple loops. But i am looking for more advanced usage of the functional programing is Swift.
My experiment:
fisrtArray = zip(fisrtArray, secondArray).map()
The main problem i do not know how to write condition in the map function. Condition should be:
if ($0.id == $1.id) {
$0.name = $1.name
}
From the comment discussing it is possible to highlight that zip is not suitable in my case because we should iterate over all array to find if we have similar id's that are not in the same order.
The following code does work independently by the order of the elements inside the 2 arrays
firstArray = firstArray.map { (item) -> Item in
guard
let index = secondArray.index(where: { $0.id == item.id })
else { return item }
var item = item
item.name = secondArray[index].name
return item
}
"[Item(id: 1, name: "Bogdan", value: 3), Item(id: 2, name: "Max", value: 5)]\n"
Update
The following version uses the first(where: method as suggested by Martin R.
firstArray = firstArray.map { item -> Item in
guard let secondElm = secondArray.first(where: { $0.id == item.id }) else { return item }
var item = item
item.name = secondElm.name
return item
}
A solution for your specific problem above would be:
struct Item {
var id: Int
var name: String
}
let first = Item(id: 1, name: "Oleg")
let second = Item(id: 2, name: "Olexander")
let firstInSecond = Item(id: 1, name: "Bogdan")
let secondInSecond = Item(id: 2, name: "Max")
let ret = zip([first, second], [firstInSecond, secondInSecond]).map({
return $0.id == $1.id ? $1 : $0
})
=> But it requires that there are as many items in the first as in the second array - and that they have both the same ids in the same order...
The map function cannot directly mutate its elements. And since you're using structs (passed by value), it wouldn't work anyway, because the version you see in $0 would be a different instance than the one in the array. To use map correctly, I'd use a closure like this:
fisrtArray = zip(fisrtArray, secondArray).map() {
return Item(id: $0.id, name: $1.name, value: $0.value)
}
This produces the result you're expecting.
Now, if your structs were objects (value types instead of reference types), you could use forEach and do the $0.name = $1.name in there.