array of object into array of object but different (javascript) - javascript

Using javascript, I have this array:
people = [{name: carlo, lastname: Garcia, age: 28},
{name: maria, lastname: pia, age: 20},
{name: elly, lastname: martinez, age: 25}]
I would like to transform it into:
arrayList = [{data: {name: carlo, lastname: garcia, age: 28}, checked: false},
{data: {name: carlo, lastname: garcia, age: 28}, checked: false},
{data: {name: carlo, lastname: garcia, age: 28}, checked: false}]
How can I do it?

You want to use Array.prototype.map
var people = [{ name: "carlo", lastname: "Garcia", age: 28 }, { name: "maria", lastname: "pia", age: 20 }, { name: "elly", lastname: "martinez", age: 25 }]
var arrayList = people.map(person => ({
data: person,
checked: false,
}))
console.log(arrayList);

Just use map(). Return an object with data and checked fields.
Where:
data is set to each person
checked is set to false
people = [{name: 'carlo', lastname: 'Garcia', age: 28},{name: 'maria', lastname: 'pia', age: 20},{name: 'elly', lastname: 'martinez', age: 25}]
arrayList = people.map(p => ({ data: p, checked: false }))
console.log(arrayList)

Related

Get all unique values from objects and assign them into array under correct key

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

Remove duplicate objects from an array with Keys

How to filter array of objects by property? for example in this array if two or more objects have same properties like name and lastname I want to remove either of them and leave only unique one in an array. example arr:
[ {name: "George", lastname: "GeorgeLast", age: 12},
{name: "George", lastname: "GeorgeLast", age: 13},
{name: "Bob", lastname: "GeorgeLast", age: 12}]
result should be either
[ {name: "George", lastname: "GeorgeLast", age: 13},
{name: "Bob", lastname: "GeorgeLast", age: 12}]
or
[ {name: "George", lastname: "GeorgeLast", age: 12},
{name: "Bob", lastname: "GeorgeLast", age: 12}]
Apply the technique shown in this answer, which is:
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
...but using findIndex with some criteria rather than just indexOf.
let people = [
{ name: "George", lastname: "GeorgeLast", age: 12 },
{ name: "George", lastname: "GeorgeLast", age: 13 },
{ name: "Bob", lastname: "GeorgeLast", age: 12 }
]
let result = people.filter(
(person, index) => index === people.findIndex(
other => person.name === other.name
&& person.lastname === other.lastname
));
console.log(result);
As for whether it keeps 12-year-old George or 13-year-old George, it is a matter of how findIndex works, which so happens to return the first matching element. So in your example case it will keep 12-year-old George.
The Map object holds key-value pairs and remembers the original insertion order of the keys.
const arr = [
{ name: "George", lastname: "GeorgeLast", age: 12 },
{ name: "George", lastname: "GeorgeLast", age: 13 },
{ name: "Bob", lastname: "GeorgeLast", age: 12 }
];
const newMap = new Map();
arr.forEach((item) => newMap.set(item.name, item));
console.log([...newMap.values()]);
Another solution.
Here you don't need to iterate through the list n*n/2 times (if I count correctly).
On the other hand, this one looks less concise and uses more memory.
Use whichever you prefer.
const arr = [
{name: "George", lastname: "GeorgeLast", age: 12},
{name: "George", lastname: "GeorgeLast", age: 13},
{name: "Bob", lastname: "GeorgeLast", age: 12}
];
const obj = {}
arr.forEach(v => {
if (!obj[v.name]) {
obj[v.name] = {}
}
if (!obj[v.name][v.lastname]) {
obj[v.name][v.lastname] = v;
}
})
const result = [];
Object.values(obj).forEach(nameObj =>
Object.values(nameObj).forEach(surnObj => result.push(surnObj))
);
console.log(result)

lodash find returns only one result

I'm using lodash find, and on my test, it is only returning one result, is this the expected response? how to find all instances?
var users = [
{ firstName: "John", lastName: "Doe", age: 28, gender: "male" },
{ firstName: "Jane", lastName: "Doe", age: 5, gender: "female" },
{ firstName: "Jim", lastName: "Carrey", age: 54, gender: "male" },
{ firstName: "Kate", lastName: "Winslet", age: 40, gender: "female" }
];
var encontre = _.find(users, { lastName: "Doe" })
console.log("usuario encontre::", encontre)
response
usuario encontre:: { firstName: 'John', lastName: 'Doe', age: 28,
gender: 'male' }
so how to seethe 2 users with lastName: Doe?
thanks
Try with _.filter as _.find returns the first matched element.
_.filter will return an array of all matched elements.
var users = [
{ firstName: "John", lastName: "Doe", age: 28, gender: "male" },
{ firstName: "Jane", lastName: "Doe", age: 5, gender: "female" },
{ firstName: "Jim", lastName: "Carrey", age: 54, gender: "male" },
{ firstName: "Kate", lastName: "Winslet", age: 40, gender: "female" }
];
var encontre = _.filter(users, { lastName: "Doe" })
console.log("usuario encontre::", encontre)
jsfiddle for ref : https://jsfiddle.net/c_Dhananjay/b6ngxhvp/

Add count value to object with same key values (array of objects)

Hello I have kind of complicated iteration to be done over an array of objects. I have array like this:
[
{ name: 'Jacob', lastName: 'Smith', dob: '1995-11-29' },
{ name: 'Jacob', lastName: 'Smith', dob: '1991-08-21' },
{ name: 'Ann', lastName: 'Smith', dob: '1995-11-29' },
{ name: 'Ann', lastName: 'Nansen', dob: '1983-01-01' },
{ name: 'Jacob', lastName: 'Smith', dob: '1985-06-15' },
{ name: 'Jacob', lastName: 'Smith', dob: '1995-11-29' },
{ name: 'Ann', lastName: 'Smith', dob: '2010-11-29' },
]
I would like to add count property to each object that counts objects with same name and surname... So it should be now:
[
{ name: 'Jacob', lastName: 'Smith', count: 4 },
{ name: 'Ann', lastName: 'Smith', count: 2 },
{ name: 'Ann', lastName: 'Nansen', count: 1' },
]
You can use Array.reduce and Object.values
Convert array in an object with key as name and last name combination with value being the resulting object.
From the object, get all values as the final result
let arr = [{ name: 'Jacob', lastName: 'Smith', dob: '1995-11-29' },{ name: 'Jacob', lastName: 'Smith', dob: '1991-08-21' },{ name: 'Ann', lastName: 'Smith', dob: '1995-11-29' },{ name: 'Ann', lastName: 'Nansen', dob: '1983-01-01' },{ name: 'Jacob', lastName: 'Smith', dob: '1985-06-15' },{ name: 'Jacob', lastName: 'Smith', dob: '1995-11-29' },{ name: 'Ann', lastName: 'Smith', dob: '2010-11-29' }];
let result = Object.values(arr.reduce((a,{name, lastName}) => {
let key = `${name}_${lastName}`;
a[key] = a[key] || {name, lastName, count : 0};
a[key].count++;
return a;
}, {}));
console.log(result);
const hash = [];
for(const { name, lastName } of persons) {
const key = name + "/" + lastName;
if(!hash[key]) hash[key] = {
name,
lastName,
count: 0,
};
hash[key].count++;
}
const result = Object.values(hash);
You could use JSON.stringify to combine name and last name in a safe way. I like using a Map to group the records with the same keys together:
const data = [{ name: 'Jacob', lastName: 'Smith', dob: '1995-11-29' },{ name: 'Jacob', lastName: 'Smith', dob: '1991-08-21' },{ name: 'Ann', lastName: 'Smith', dob: '1995-11-29' },{ name: 'Ann', lastName: 'Nansen', dob: '1983-01-01' },{ name: 'Jacob', lastName: 'Smith', dob: '1985-06-15' },{ name: 'Jacob', lastName: 'Smith', dob: '1995-11-29' },{ name: 'Ann', lastName: 'Smith', dob: '2010-11-29' }];
const keyed = data.map(o => [JSON.stringify([o.name, o.lastName]), o]);
const map = new Map(keyed.map(([key, {name, lastName}]) =>
[key, {name, lastName, count: 0}]));
keyed.forEach(([key, o]) => map.get(key).count++);
const result = Array.from(map.values());
console.log(result);
let arr=[
{ name: 'Jacob', lastName: 'Smith', dob: '1995-11-29' },
{ name: 'Jacob', lastName: 'Smith', dob: '1991-08-21' },
{ name: 'Ann', lastName: 'Smith', dob: '1995-11-29' },
{ name: 'Ann', lastName: 'Nansen', dob: '1983-01-01' },
{ name: 'Jacob', lastName: 'Smith', dob: '1985-06-15' },
{ name: 'Jacob', lastName: 'Smith', dob: '1995-11-29' },
{ name: 'Ann', lastName: 'Smith', dob: '2010-11-29' },
];
let outerArr=[];
for(arrValue of arr)
{
delete arrValue.dob
let index=outerArr.findIndex(item=> item.name==arrValue.name &&
item.lastName==arrValue.lastName);
if(index==-1)
{
let arrFind=arr.filter(item=> item.name==arrValue.name &&
item.lastName==arrValue.lastName)
arrValue.count=arrFind.length
outerArr.push(arrValue)
}
}
console.log('result',outerArr)
You can achieve this by reducing the original Array.
As you iterate through the people you can check if they have already been "grouped" using Array.some - if they haven't, push your built person Object to the previously returned Array.
const getInstances = ({ name, lastName }, data) => data.filter(d => d.name === name && d.lastName === lastName).length
const people = [
{ name: 'Jacob', lastName: 'Smith', dob: '1995-11-29' },
{ name: 'Jacob', lastName: 'Smith', dob: '1991-08-21' },
{ name: 'Ann', lastName: 'Smith', dob: '1995-11-29' },
{ name: 'Ann', lastName: 'Nansen', dob: '1983-01-01' },
{ name: 'Jacob', lastName: 'Smith', dob: '1985-06-15' },
{ name: 'Jacob', lastName: 'Smith', dob: '1995-11-29' },
{ name: 'Ann', lastName: 'Smith', dob: '2010-11-29' },
]
const groupedPeople = people.reduce((group, person, i, people) => {
const alreadyBeenGrouped = group.some(({ name, lastName }) => name === person.name && lastName === person.lastName)
if (!alreadyBeenGrouped) {
group.push({
name: person.name,
lastName: person.lastName,
count: getInstances(person, people)
})
}
return group
}, [])
console.log(groupedPeople)

reduce an array of objects in javascript

how can I reduce an array of objects of this type:
[
{id: 1, name: 'jhon', lastname: 'doe', age: 30},
{id: 2, name: 'max', lastname: 'wall', age: 20},
{id: 3, name: 'fer', lastname: 'baneg', age: 15}
]
I need to get a new array just with these values:
[
{id: 1, name: 'jhon'},
{id: 2, name: 'max'},
{id: 3, name: 'fer'}
]
You can use map() method for this with ES6 parameter destructuring.
const data = [{id: 1, name: 'jhon', lastname: 'doe', age: 30},{id: 2, name: 'max', lastname: 'wall', age: 20},{id: 3, name: 'fer', lastname: 'baneg', age: 15}]
const result = data.map(({id, name}) => ({id, name}))
console.log(result)

Categories

Resources