How can I group data in Angular 2 with TypeScript. I am aware that this is done using "group by" filter in Angular 1.X, but not getting how to group data in Angular 2. I have this array:
import {Employee} from './employee';
export var employees: Employee[];
employees = [
{ id: 1, firstName: "John", lastName: "Sonmez", department: 1, age: 24, address: "24/7, Working hours apartment, Cal. US", contactNumber: "+968546215789" },
{ id: 2, firstName: "Mark", lastName: "Seaman", department: 2, age: 25, address: "32-C, Happy apartments, Block-9C, Cal. US", contactNumber: "+968754216984" },
{ id: 3, firstName: "Jamie", lastName: "King", department: 3, age: 32, address: "54/II, Glorydale apartment, Cal. US", contactNumber: "+967421896326" },
{ id: 5, firstName: "Jacob", lastName: "Ridley", department: 5, age: 24, address: "24/7, Working hours apartment, Cal. US", contactNumber: "+968546215789" },
{ id: 6, firstName: "Peter", lastName: "Parker", department: 3, age: 25, address: "32-C, Happy apartments, Block-9C, Cal. US", contactNumber: "+968754216984" },
{ id: 7, firstName: "Martin", lastName: "Luther", department: 4, age: 32, address: "54/II, Glorydale apartment, Cal. US", contactNumber: "+967421896326" },
{ id: 8, firstName: "Raghav", lastName: "Kumar", department: 1, age: 34, address: "51/C Shivalik, Cal. US", contactNumber: "+967842569842" },
{ id: 9, firstName: "Narayan", lastName: "Sonmez", department: 3, age: 24, address: "24/7, Working hours apartment, Cal. US", contactNumber: "+968546215789" },
{ id: 10, firstName: "Russell", lastName: "Andre", department: 2, age: 25, address: "32-C, Happy apartments, Block-9C, Cal. US", contactNumber: "+968754216984" },
{ id: 11, firstName: "Ramona", lastName: "King", department: 4, age: 32, address: "54/II, Glorydale apartment, Cal. US", contactNumber: "+967421896326" },
{ id: 12, firstName: "Andre", lastName: "Russell", department: 1, age: 34, address: "51/C Shivalik, Cal. US", contactNumber: "+967842569842" },
{ id: 13, firstName: "Nathan", lastName: "Leon", department: 1, age: 24, address: "24/7, Working hours apartment, Cal. US", contactNumber: "+968546215789" },
{ id: 14, firstName: "Brett", lastName: "Lee", department: 5, age: 25, address: "32-C, Happy apartments, Block-9C, Cal. US", contactNumber: "+968754216984" },
{ id: 15, firstName: "Tim", lastName: "Cook", department: 2, age: 32, address: "54/II, Glorydale apartment, Cal. US", contactNumber: "+967421896326" },
{ id: 16, firstName: "Steve", lastName: "Jobs", department: 5, age: 34, address: "51/C Shivalik, Cal. US", contactNumber: "+967842569842" }
];
and I am looking to count the employees by department, like
Department 1 has 4 employees
and so on.
Joining the department id with actual department (so that I can get the department name) is another story I need to figure out.
I would create a custom pipe to do that as described below:
#Pipe({name: 'groupBy'})
export class GroupByPipe implements PipeTransform {
transform(value: Array<any>, field: string): Array<any> {
const groupedObj = value.reduce((prev, cur)=> {
(prev[cur[field]] = prev[cur[field]] || []).push(cur);
return prev;
}, {});
return Object.keys(groupedObj).map(key => ({ key, value: groupedObj[key] }));
}
}
And then on your template you can write:
<div *ngFor="let item of employees | groupBy: 'department'">
Department {{ item.key }} has {{ item.value.length }} employees
</div>
See also corresponding plunker https://plnkr.co/edit/49fWY1rMbSZtNQ3H
You can use ngx-pipes https://github.com/danrevah/ngx-pipes#groupby
this.arrayObject = [
{id: 1, elm: 'foo', value: 0},
{id: 2, elm: 'bar', value: 1},
{id: 3, elm: 'foo', value: 2},
{id: 4, elm: 'foo', value: 2}
];
this.arrayNestedObject = [
{id: 1, prop: { deep: 'foo' }},
{id: 2, prop: { deep: 'bar' }},
{id: 3, prop: { deep: 'foo' }},
{id: 4, prop: { deep: 'bar' }}
];
<p>{{ arrayObject | groupBy: 'elm' }}</p>
<!-- Output: "{foo: [{id: 1, elm: 'foo', value: 0}, {id: 3, elm: 'foo', value: 2}, {id: 4, elm: 'foo', value: 2}], bar: [{id: 2, elm: 'bar', value: 1}]}" -->
var dept = employees.map((m) => m.department).filter((f, i, ar) => ar.indexOf(f) === i);
console.log(dept);
var group = employees.reduce((accumulator, item, i, arr) => {
if (dept.length) {
var pop = dept.shift();
var list = arr.filter((f) => f.department == pop);
accumulator.push(...list);
}
return accumulator;
}, []);
console.log(group);
If you need to access nested properties or need to compare objects you can do
#Pipe({ name: 'groupByProperty' })
export class GroupByPropertyPipe implements PipeTransform {
transform(value: Array<any>, property: string): Array<any> {
if (!value) {
return null;
}
const group = value.reduce((previous, current) => {
const parts = property.split('.');
let currentValue: any;
parts.forEach(part => {
currentValue = currentValue ? currentValue[part] : current[part];
});
// Stringify objects for comparison
currentValue = typeof currentValue === 'object' ? JSON.stringify(currentValue) : currentValue;
if (!previous[currentValue]) {
previous[currentValue] = [current];
} else {
previous[currentValue].push(current);
}
return previous;
}, {});
return Object.keys(group).map(key => ({ key, value: group[key] }));
}
}
Related
I have list contact like this, i try to find anwser my question in SOF but have not, can u guys help me? thank you
export const rows = [
{
id: 1,
name: 'Snow',
email: 'Jon',
contact: 35,
avatar: ''
},
{ id: 2, name: 'Lannister', email: 'Cersei', contact: 42,
avatar: '' },
{ id: 3, name: 'Lannister', email: 'Jaime', contact: 45,
avatar: '' },
{ id: 4, name: 'Stark', email: 'Arya', contact: 16,
avatar: '' },
{ id: 5, name: 'Targaryen', email: 'Daenerys', contact: null,
avatar: '' },
{ id: 6, name: 'Melisandre', email: null, contact: 150,
avatar: '' },
{ id: 7, name: 'Clifford', email: 'Ferrara', contact: 44,
avatar: '' },
{ id: 8, name: 'Frances', email: 'Rossini', contact: 36,
avatar: '' },
{ id: 9, name: 'Roxie', email: 'Harvey', contact: 65,
avatar: '' },
{ id: 11, name: 'Snow', email: 'Jon', contact: 35 ,
avatar: ''},
{ id: 12, name: 'Lannister', email: 'Cersei', contact: 42,
avatar: '' },
];
and i want render it like this:
const rows = [
{
id: 1,
name: "Snow",
email: "Jon",
contact: 35,
avatar: "",
},
{ id: 2, name: "Lannister", email: "Cersei", contact: 42, avatar: "" },
{ id: 3, name: "Lannister", email: "Jaime", contact: 45, avatar: "" },
{ id: 4, name: "Stark", email: "Arya", contact: 16, avatar: "" },
{ id: 5, name: "Targaryen", email: "Daenerys", contact: null, avatar: "" },
{ id: 6, name: "Melisandre", email: null, contact: 150, avatar: "" },
{ id: 7, name: "Clifford", email: "Ferrara", contact: 44, avatar: "" },
{ id: 8, name: "Frances", email: "Rossini", contact: 36, avatar: "" },
{ id: 9, name: "Roxie", email: "Harvey", contact: 65, avatar: "" },
{ id: 11, name: "Snow", email: "Jon", contact: 35, avatar: "" },
{ id: 12, name: "Lannister", email: "Cersei", contact: 42, avatar: "" },
];
const sortedArray = rows.sort((current, next) => current.name > next.name ? 1 : next.name > current.name ? -1 : 0 )
console.log(sortedArray)
I am not sure what your exact question is, but maybe I can give you a starting point:
const grouped = rows.reduce(
(groupedRows, row) => {
const firstLetter = row.name.slice(0,1);
return {
...groupedRows,
[firstLetter]: [...(groupedRows[firstLetter] || []), row]
}
}, {}
)
This will give you an Object like
{ L: [
{ id: 2, name: 'Lannister', email: 'Cersei', contact: 42, avatar: '' },
{ id: 3, name: 'Lannister', email: 'Jaime', contact: 45, avatar: '' }
],
S: [
{ id: 4, name: 'Stark', email: 'Arya', contact: 16, avatar: '' },
]
// etc.
}
Then use Object.entries(grouped) to turn this into a sequence that you can iterate over and build your UI.
I have an array of objects to be converted to an object with an array of unique values assigned to the same keys.
How can I get this output?
//input
let users = [
{ id: 1, name: "Alan", surname: "Davis", age: 34, isAdmin: 'yes'},
{ id: 2, name: "John", surname: "Doe", age: 35, isAdmin: 'no'},
{ id: 3, name: "Monica", surname: "Bush", age: 25, isAdmin: 'no'},
{ id: 4, name: "Sandra", surname: "Back", age: 23, isAdmin: 'no'},
{ id: 5, name: "Jacob", surname: "Front", age: 34, isAdmin: 'yes'},
];
//output
let unique = {
id: [1, 2, 3 ,4 ,5],
name: ['Alan', 'John', 'Monica', 'Sandra', 'Jacob'],
surname: ['Davis', 'Doe', 'Bush', 'Back', 'Front'],
age: [34, 35, 25, 23],
isAdmin: ['yes', 'no'],
}
You can use Array.prototype.reduce() and for all of the items iterate over with Array.prototype.forEach() and creating a unique array with Set
Code:
const users = [{ id: 1, name: 'Alan', surname: 'Davis', age: 34, isAdmin: 'yes' },{ id: 2, name: 'John', surname: 'Doe', age: 35, isAdmin: 'no' },{ id: 3, name: 'Monica', surname: 'Bush', age: 25, isAdmin: 'no' },{ id: 4, name: 'Sandra', surname: 'Back', age: 23, isAdmin: 'no' },{ id: 5, name: 'Jacob', surname: 'Front', age: 34, isAdmin: 'yes' },]
const unique = users.reduce((a, c) => (
Object
.entries(c)
.forEach(([k, v]) => a[k] = [...new Set([...(a[k] || []), v])]),
a
), {})
console.log(unique)
Here's one way
Iterate over the keys of the first object in the array to produce a list of keys
Create an array of the corresponding values. Filter the array for dupes.
Wrap the keys and values back into an object
let users = [
{ id: 1, name: "Alan", surname: "Davis", age: 34, isAdmin: 'yes'},
{ id: 2, name: "John", surname: "Doe", age: 35, isAdmin: 'no'},
{ id: 3, name: "Monica", surname: "Bush", age: 25, isAdmin: 'no'},
{ id: 4, name: "Sandra", surname: "Back", age: 23, isAdmin: 'no'},
{ id: 5, name: "Jacob", surname: "Front", age: 34, isAdmin: 'yes'},
];
let unique = Object.fromEntries(
Object.keys(users[0]).map(k =>
[k, users.map(u => u[k]).filter((value, i, arr) => arr.indexOf(value) === i)]
)
);
console.log(unique);
I have some data that looks like :
{
_id: "5e985a07feddae7617ac44f6",
age: 24,
eyeColor: "brown",
name: "Cummings Baxter",
gender: "male",
company: "VELOS",
email: "cummingsbaxter#velos.com",
phone: "+1 (907) 482-2451",
tags: ["labore", "elit", "excepteur", "nisi", "mollit", "anim", "aliquip"],
friends: [
{
id: 0,
name: "Sheppard Jensen",
},
],
},
{
_id: "5e985a0709dfa1e6fd93c6ad",
age: 32,
eyeColor: "brown",
name: "Madelyn Dickson",
gender: "female",
company: "KENGEN",
email: "madelyndickson#kengen.com",
phone: "+1 (984) 521-2439",
tags: ["nisi", "veniam", "dolore", "officia", "ex", "non", "pariatur"],
friends: [
{
id: 0,
name: "Bruce Barton",
},
{
id: 1,
name: "Juliet Schmidt",
},
{
id: 2,
name: "Horton Haley",
},
{
id: 3,
name: "Herminia Witt",
},
],
},
{
_id: "5e985a0737e2306e9aef6ecd",
age: 26,
eyeColor: "blue",
name: "Mcguire Mercado",
gender: "male",
company: "LINGOAGE",
email: "mcguiremercado#lingoage.com",
phone: "+1 (963) 450-2194",
tags: ["cupidatat", "occaecat", "amet", "qui", "elit", "esse", "deserunt"],
friends: [
{
id: 0,
name: "Loraine Harper",
},
{
id: 1,
name: "Luann Randall",
},
{
id: 2,
name: "Obrien Rich",
},
{
id: 3,
name: "Noble Wilkerson",
},
],
},
{
_id: "5e985a07148cfba58c860ec2",
age: 26,
eyeColor: "brown",
name: "Marina Porter",
gender: "female",
company: "GORGANIC",
email: "marinaporter#gorganic.com",
phone: "+1 (867) 417-3497",
tags: [
"laborum",
"aliquip",
"sit",
"adipisicing",
"aute",
"cupidatat",
"aliquip",
],
friends: [
{
id: 0,
name: "Blair Hill",
},
{
id: 1,
name: "Ebony Jimenez",
},
],
},
{
_id: "5e985a074984f9f08ccaaa4c",
age: 255,
eyeColor: "green",
name: "Barlow Ferguson",
gender: "male",
company: "TOYLETRY",
email: "barlowferguson#toyletry.com",
phone: "+1 (837) 484-2231",
tags: ["est", "dolor", "minim", "ut", "anim", "culpa", "non"],
friends: [
{
id: 0,
name: "Delacruz Acevedo",
},
{
id: 1,
name: "Gloria Tanner",
},
{
id: 2,
name: "Cantrell Myers",
},
{
id: 3,
name: "Fisher Leonard",
},
{
id: 3,
name: "Gloria Tenner",
},
],
},
];
I want to write a function that recursively filters for desired word and returns object which contains that word.
example : function filterWith(data, "Sheppard Jensen") would return
_id: "5e985a07feddae7617ac44f6",
age: 24,
eyeColor: "brown",
name: "Cummings Baxter",
gender: "male",
company: "VELOS",
email: "cummingsbaxter#velos.com",
phone: "+1 (907) 482-2451",
tags: ["labore", "elit", "excepteur", "nisi", "mollit", "anim", "aliquip"],
friends: [
{
id: 0,
name: "Sheppard Jensen",
},
],
},
I could do this non-recursively but since resursive way could be much more efficient I want to know the way to do this. Would really apreciate any help.
here is a simple way , because JSON.stringify itself use recursively way
function filterWith(data, str) {
return data.filter(each => JSON.stringify(each).indexOf(str) > -1)
}
but you would like to do it by yourself, you can try this way
function filterWith(data, str) {
const isTarget = (_, str) => _.indexOf(str) > -1;
const $filterWith = ($data) => {
if ($data === undefined || $data === null) {
return false;
}
if (typeof $data != 'object' ) {
return isTarget(`${$data}`, `${str}`)
}
if (Array.isArray($data)) {
for (let i of $data) {
if ($filterWith($data[i])) return true
}
}
for (let i in $data) {
if (isTarget(`${data}`, `${i}`) || $filterWith($data[i])) return true
}
return false
}
return data.filter(each => $filterWith(each))
}
I would write a fairly simple recursive check that a given object contains a the string and then write a trivail filter on top of this.
const hasString = (str) => (obj) =>
Array.isArray (obj)
? obj .some (hasString (str))
: Object (obj) === obj
? hasString (str) (Object. values (obj))
: typeof obj === 'string'
? obj .includes (str)
: false
const filterWith = (xs, str) =>
xs .filter (hasString (str))
const input = [{_id: "5e985a07feddae7617ac44f6", age: 24, eyeColor: "brown", name: "Cummings Baxter", gender: "male", company: "VELOS", email: "cummingsbaxter#velos.com", phone: "+1 (907) 482-2451", tags: ["labore", "elit", "excepteur", "nisi", "mollit", "anim", "aliquip"], friends: [{id: 0, name: "Sheppard Jensen"}]}, {_id: "5e985a0709dfa1e6fd93c6ad", age: 32, eyeColor: "brown", name: "Madelyn Dickson", gender: "female", company: "KENGEN", email: "madelyndickson#kengen.com", phone: "+1 (984) 521-2439", tags: ["nisi", "veniam", "dolore", "officia", "ex", "non", "pariatur"], friends: [{id: 0, name: "Bruce Barton"}, {id: 1, name: "Juliet Schmidt"}, {id: 2, name: "Horton Haley"}, {id: 3, name: "Herminia Witt"}]}, {_id: "5e985a0737e2306e9aef6ecd", age: 26, eyeColor: "blue", name: "Mcguire Mercado", gender: "male", company: "LINGOAGE", email: "mcguiremercado#lingoage.com", phone: "+1 (963) 450-2194", tags: ["cupidatat", "occaecat", "amet", "qui", "elit", "esse", "deserunt"], friends: [{id: 0, name: "Loraine Harper"}, {id: 1, name: "Luann Randall"}, {id: 2, name: "Obrien Rich"}, {id: 3, name: "Noble Wilkerson"}]}, {_id: "5e985a07148cfba58c860ec2", age: 26, eyeColor: "brown", name: "Marina Porter", gender: "female", company: "GORGANIC", email: "marinaporter#gorganic.com", phone: "+1 (867) 417-3497", tags: ["laborum", "aliquip", "sit", "adipisicing", "aute", "cupidatat", "aliquip"], friends: [{id: 0, name: "Blair Hill"}, {id: 1, name: "Ebony Jimenez"}]}, {_id: "5e985a074984f9f08ccaaa4c", age: 255, eyeColor: "green", name: "Barlow Ferguson", gender: "male", company: "TOYLETRY", email: "barlowferguson#toyletry.com", phone: "+1 (837) 484-2231", tags: ["est", "dolor", "minim", "ut", "anim", "culpa", "non"], friends: [{id: 0, name: "Delacruz Acevedo"}, {id: 1, name: "Gloria Tanner"}, {id: 2, name: "Cantrell Myers"}, {id: 3, name: "Fisher Leonard"}, {id: 3, name: "Gloria Tenner"}]}]
console .log (filterWith (input, 'Sheppard Jensen'))
.as-console-wrapper {max-height: 100% !important; top: 0}
hasString checks if the input is an array, and if it is, simply recurs over its children until it finds a match, returning false if none match. If the input is an object, we do the same thing with its keys. If the input is a string, we see if it includes the target value. (You might prefer an equality check here.) And if it's not a string, object, or array, it returns false.
filterWith is a simple wrapper that filters an input array using hasString.
Is it possible to iterate over the array, excluding the first element (omit the first object in the array)?
CODE:
let multipleDemo =[];
let people = [
{ name: 'Adam', email: 'adam#email.com', age: 12,
country: 'United States' },
{ name: 'Amalie', email: 'amalie#email.com', age: 12,
country: 'Argentina' },
{ name: 'Estefanía', email: 'estefania#email.com', age: 21,
country: 'Argentina' },
{ name: 'Adrian', email: 'adrian#email.com', age: 21,
country: 'Ecuador' },
{ name: 'Wladimir', email: 'wladimir#email.com', age: 30,
country: 'Ecuador' },
{ name: 'Samantha', email: 'samantha#email.com', age: 30,
country: 'United States' },
{ name: 'Nicole', email: 'nicole#email.com', age: 43,
country: 'Colombia' },
{ name: 'Natasha', email: 'natasha#email.com', age: 54,
country: 'Ecuador' },
{ name: 'Michael', email: 'michael#email.com', age: 15,
country: 'Colombia' },
{ name: 'Nicolás', email: 'nicolas#email.com', age: 43,
country: 'Colombia' }
];
for(var i =0; i < people.length; i++) {
multipleDemo.push(people[i]);
people.splice(people[i], 1000);
console.log(multipleDemo);
console.log(people);
}
Example code: https://plnkr.co/edit/UJfRUs6dAT1NC1EnOvqA?p=preview
I want to leave { name: 'Adam', email: 'adam#email.com', age: 12, country: 'United States' } in array people. Rest of elements I want to put in array multipleDemo
I want such as FINISH EFFECT:
let multipleDemo =[,
{ name: 'Amalie', email: 'amalie#email.com', age: 12,
country: 'Argentina' },
{ name: 'Estefanía', email: 'estefania#email.com', age: 21,
country: 'Argentina' },
{ name: 'Adrian', email: 'adrian#email.com', age: 21,
country: 'Ecuador' },
{ name: 'Wladimir', email: 'wladimir#email.com', age: 30,
country: 'Ecuador' },
{ name: 'Samantha', email: 'samantha#email.com', age: 30,
country: 'United States' },
{ name: 'Nicole', email: 'nicole#email.com', age: 43,
country: 'Colombia' },
{ name: 'Natasha', email: 'natasha#email.com', age: 54,
country: 'Ecuador' },
{ name: 'Michael', email: 'michael#email.com', age: 15,
country: 'Colombia' },
{ name: 'Nicolás', email: 'nicolas#email.com', age: 43,
country: 'Colombia' }];
let people = [
{ name: 'Adam', email: 'adam#email.com', age: 12,
country: 'United States' }
];
You can use Array.prototype.slice() to modify your arrays to get your desired output.
let people = [{
name: 'Adam',
email: 'adam#email.com',
age: 12,
country: 'United States'
},
{
name: 'Amalie',
email: 'amalie#email.com',
age: 12,
country: 'Argentina'
},
{
name: 'Estefanía',
email: 'estefania#email.com',
age: 21,
country: 'Argentina'
},
{
name: 'Adrian',
email: 'adrian#email.com',
age: 21,
country: 'Ecuador'
},
{
name: 'Wladimir',
email: 'wladimir#email.com',
age: 30,
country: 'Ecuador'
},
{
name: 'Samantha',
email: 'samantha#email.com',
age: 30,
country: 'United States'
},
{
name: 'Nicole',
email: 'nicole#email.com',
age: 43,
country: 'Colombia'
},
{
name: 'Natasha',
email: 'natasha#email.com',
age: 54,
country: 'Ecuador'
},
{
name: 'Michael',
email: 'michael#email.com',
age: 15,
country: 'Colombia'
},
{
name: 'Nicolás',
email: 'nicolas#email.com',
age: 43,
country: 'Colombia'
}
];
let multipleDemo = people.slice(1);
people = people.slice(0, 1);
console.log(multipleDemo);
console.log('--------------------');
console.log(people);
You can use Array Destructuring to unpack and assign remaining part of the array to a variable using rest pattern and use .forEach() to iterate over them as follows:
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const [first, ...rest] = arr;
rest.forEach(v => console.log(v));
.as-console-wrapper { max-height: 100% !important; top: 0; }
There are many ways to achieve this. but the easiest and concise solution would be using the filter(). Which returns an array that contains each element where the condition is met.
let people = [
{ name: 'Adam', email: 'adam#email.com', age: 12,
country: 'United States' },
{ name: 'Amalie', email: 'amalie#email.com', age: 12,
country: 'Argentina' },
{ name: 'Estefanía', email: 'estefania#email.com', age: 21,
country: 'Argentina' },
{ name: 'Adrian', email: 'adrian#email.com', age: 21,
country: 'Ecuador' },
{ name: 'Wladimir', email: 'wladimir#email.com', age: 30,
country: 'Ecuador' },
{ name: 'Samantha', email: 'samantha#email.com', age: 30,
country: 'United States' },
{ name: 'Nicole', email: 'nicole#email.com', age: 43,
country: 'Colombia' },
{ name: 'Natasha', email: 'natasha#email.com', age: 54,
country: 'Ecuador' },
{ name: 'Michael', email: 'michael#email.com', age: 15,
country: 'Colombia' },
{ name: 'Nicolás', email: 'nicolas#email.com', age: 43,
country: 'Colombia' }
];
let multipleDemo = people.filter((v, k) => k !== 0);
people = people.filter((v, k) => k === 0);
console.log(multipleDemo)
console.log(people)
You can use .slice() to omit n elements from the beginning.
Array.slice(1) means you take the array starting from index 1 to the end.
You can also define until which element you want to slice off.
Array.slice(1, 3) will slice the elements of index 1 and 2. It will be Amalie and Estefanía in this case.
let people = [
{ name: "Adam", email: "adam#email.com", age: 12, country: "United States" },
{ name: "Amalie", email: "amalie#email.com", age: 12, country: "Argentina" },
{ name: "Estefanía", email: "estefania#email.com", age: 21, country: "Argentina" },
{ name: "Adrian", email: "adrian#email.com", age: 21, country: "Ecuador" },
{ name: "Wladimir", email: "wladimir#email.com", age: 30, country: "Ecuador" },
{ name: "Samantha", email: "samantha#email.com", age: 30, country: "United States" },
{ name: "Nicole", email: "nicole#email.com", age: 43, country: "Colombia" },
{ name: "Natasha", email: "natasha#email.com", age: 54, country: "Ecuador" },
{ name: "Michael", email: "michael#email.com", age: 15, country: "Colombia" },
{ name: "Nicolás", email: "nicolas#email.com", age: 43, country: "Colombia" }
];
let multipleDemo = people.slice(1);
multipleDemo.forEach(function (current) {
console.log(current.name);
});
Since you simply want to copy the elements from people array to multipleDemo array excluding the first element, you could use slice() array method.
multipleDemo = people.slice(1)
.slice(1) will copy the contents of people array from index1 without reference to the multipleDemo array.
.slice() in MDN
My service give result as follows
$scope.ListOfPeople = [
{ PersonID: 10, FirstName: "John", LastName: "Smith", Sex: "Male" },
{ PersonID: 11, FirstName: "James", LastName: "Last", Sex: "Male" },
{ PersonID: 12, FirstName: "Mary", LastName: "Heart", Sex: "Female" },
{ PersonID: 13, FirstName: "Sandra", LastName: "Goldsmith", Sex: "Female" },
{ PersonID: 14, FirstName: "Shaun", LastName: "Sheep", Sex: "Male" },
{ PersonID: 15, FirstName: "Nicola", LastName: "Smith", Sex: "Male" }
];
I need to customise my datasource as follows
$scope.output= [
{ PersonID: 10, FirstName: "John" },
{ PersonID: 11, FirstName: "James" },
{ PersonID: 12, FirstName: "Mary" },
{ PersonID: 13, FirstName: "Sandra" },
{ PersonID: 14, FirstName: "Shaun" },
{ PersonID: 15, FirstName: "Nicola" }
];
What is the best way to do this in angularjs
You can use map to achieve your goal. Take in account that the map creates new array.
$scope.output = $scope.ListOfPeople.map(function(item){
return {
PersonID: item.PersonID,
FirstName: item.FirstName
};
});
I don't think you need to create a new array to reshape it's elements. Just delete unwanted properties from your elements.
//Iterate through the array
$scope.listOfPeople.forEach(function(obj){
//Iterate through properties
for (var property in obj) {
if (['PersonId', 'FirstName'].indexOf(property) < 0) //Delete anything you don't name here
delete obj[property];
}
})