Remove all fields except some - javascript

Create a function, which removes all fields except 'firstName' and 'lastName' from the objects.
This is the code I've written. Any recommendations?
let people = [
{
firstName: 'John',
lastName: 'Clark',
gender: 'male'
},
{
firstName: 'Kaily',
lastName: 'Berserk',
gender: 'female'
},
{
firstName: 'Steven',
lastName: 'Bergeron',
gender: 'male'
}
];
function removeAllExceptNames(arr) {
let first = 'firstName';
let last = 'lastName';
return arr.forEach(p => {
if (p !== first || p !== last) {
delete arr[p];
}
})
}
console.log(removeAllExceptNames(people));
console.log(people);

I have 2 arguments in the function, the arr and the names
arr is the given array, names is the list of fields you want to keep in the array
I used forEach twice.. the first time was for the arr, the second time was for the Object's keys for each index in arr and that is where the exception names can be related to fields in the array of objects
let people = [
{
firstName: 'John',
lastName: 'Clark',
gender: 'male'
},
{
firstName: 'Kaily',
lastName: 'Berserk',
gender: 'female'
},
{
firstName: 'Steven',
lastName: 'Bergeron',
gender: 'male'
}
];
function removeAllExceptNames(arr,names) { //arr is the same, names is a list of names you want to keep
arr.forEach(a=>{
Object.keys(a).forEach(b=>{
if(!names.includes(b)){delete(a[b])}
})
})
}
removeAllExceptNames(people,["firstName","lastName"]);
console.log(people);

You can make use of map along with Object.fromEntries to get the expected output:
const people = [ { firstName: 'John', lastName: 'Clark', gender: 'male' }, { firstName: 'Kaily', lastName: 'Berserk', gender: 'female' }, { firstName: 'Steven', lastName: 'Bergeron', gender: 'male' }];
const keepProp=(arr, keepProp)=>arr.map(o=>Object.fromEntries(keepProp.map(n=>[n,o[n]])));
console.log(keepProp(people, ['firstName','lastName']))

I think we need to understand what the keyword delete does. The Mozilla Foundation says
The JavaScript delete operator removes a property from an object; if no more references to the same property are held, it is eventually released automatically.
In your scenario, you successfully removed the reference but the list is not re-ordered. It only gets replaced with an undefined. We can achieve the same thing by using the splice array function. This will remove the element and re-order.
function removeAllExceptNames(arr,firstName,lastName) {
let instancesOfNamesInArray = arr.filter(e => e.firstName == firstName || e.lastName == lastName);
// We loop through this instances and remove them from the array
instancesOfNamesInArray.foreach((item) => {
arr.splice(arr.indexOf(item),1); // Will remove the item from the array
});
}

Related

TypeScript: how to add multiple elements to an array of the same values

I would like to add multiple elements that all have the same value to an array of objects Something like '.push()' but with a count. I know I can do array.push(a, b, c), but I want to be able to do something like:
person {
firstName: string;
lastName: string;
age: number;
}
people: Person[];
numberPeople: number;
// some calculation to generate numberPeople, example: 23
person.push( {firstName: '', lastName: 'Smith', age: 0}, NumberPeople)
I know I can use a loop structure (for (i=0; i<NumberPeople;i++) person.push) but that gets cumbersome.
Is there an easier way? I'm relatively new to JavaScript and TypeScript.
I've tried .fill() but that doesn't let me specify values.
thanks,
I know I can create my own function ( mpush(obj, count) ) but I would rather use something more elegant and standard, if there is something.
To add multiple elements of objects to an array of some length with same values, we can do the following methods.
Use Array.fill
Warning: Will assign same exact object to each index of the array from 0 to length of array. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill.
type Person = { firstName: string; lastName: string; age: number; };
const numberPeople: number = 3;
const defaultPerson = { firstName: '', lastName: 'Smith', age: 0 };
// fill all ements in array with same object
const people = Array(numberPeople).fill(defaultPerson);
// when then can change one element in array by assigning new object
people[1] = { firstName: 'unique', lastName: 'unique', age: 0 };
This allows for saving memory if default values tend to be the same, and only creating new objects for unique people.
Use spread operator and Array.map
For array of different objects but same initial values, using map.
type Person = { firstName: string; lastName: string; age: number; }
const numberPeople: number = 3;
const defaultPerson: Person = { firstName: '', lastName: 'Smith', age: 0 };
const people: Person[] = [...Array(numberPeople)]
.map(_ => ({ ...defaultPerson })); // creates shallow copy of object
Use Array.from
type Person = { firstName: string; lastName: string; age: number; }
const numberPeople: number = 3;
const defaultPerson: Person = { firstName: '', lastName: 'Smith', age: 0 };
const people: Person[] = Array.from(Array(numberPeople),_=>({...defaultPerson}));
Use for...of
type Person = { firstName: string; lastName: string; age: number; }
const numberPeople: number = 3;
const defaultPerson: Person = { firstName: '', lastName: 'Smith', age: 0 };
const people: Person[]=[];
for (const _ of Array(numberPeople)) people.push({...defaultPerson})
You can use the inbuilt fill() method by first creating an Array of the right size and then populating it with a value multiple times.
interface person {
firstName: string;
lastName: string;
age: number;
}
const samplePerson = {firstName: '', lastName: 'Smith', age: 0}
const people = Array(numberPeople).fill(samplePerson)
You can use .fill() indeed:
const NumberPeople = 3;
const people = Array(NumberPeople).fill({firstName: '', lastName: 'Smith', age: 0});
console.log(people);
// notice the above method places the same person in all positions
console.log(people[2].age); // will log 0
people[1].age = 4;
console.log(people[2].age); // will log 4
//
//
// if all values being the same object is a problem, you can use .map:
const people2 = [...Array(NumberPeople)].map(_ => ({firstName: '', lastName: 'Smith', age: 0}));
console.log(people2);
console.log(people2[2].age); // will log 0
people2[1].age = 4;
console.log(people2[2].age); // will log 0
Observation : person is an object, push method will work on array. Hence, It should be people.push() instead of person.push().
Steps you can follow to achieve this requirement.
Create an array as per the numberPeople
const numberPeople = 5;
const arr = Array(numberPeople);
console.log(arr); // [undefined, undefined, undefined, undefined, undefined]
Now, Iterate this array by using Array.map() and fill with the object.
const numberPeople = 5;
const arr = Array(numberPeople);
let people = [{
firstName: 'Alpha',
lastName: 'Beta',
age: 10
}]
people.push([...arr].map(item => ({firstName: '', lastName: 'Smith', age: 0})));
console.log(people);

Search javascript object for any value

I have an array of objects. I'd like to run a global search accross all values within each object and return that object.
Data
const data = [
{
firstName: 'Brady',
lastName: 'Smith'
},
{
firstName: 'Jason',
lastName: 'Brady'
},
{
firstName: 'Michael',
lastName: 'Bolten'
}
];
How do I search for Brady across all values to return both Brady Smith and Jason Brady objects? If there is an es6 way that would be great.
Current attempt
const filteredData = data
.map(item => {
if (Object.values(item) === 'Brady') {
return item;
}
})
.filter(function(element) {
return element != null;
});
No need to map the array.
You can use filter and includes to check if a string is on the array.
const data = [{
firstName: 'Brady',
lastName: 'Smith'
},
{
firstName: 'Jason',
lastName: 'Brady'
},
{
firstName: 'Michael',
lastName: 'Bolten'
}
];
const filteredData = data.filter(o => Object.values(o).includes('Brady'));
console.log(filteredData);
You can simply use filter and find
const data = [{firstName: 'Brady',lastName: 'Smith'},{firstName: 'Jason',lastName: 'Brady'},{firstName: 'Michael',lastName: 'Bolten'}];
const filteredData = data.filter(data=>
Object.values(data).some(val=> val === 'Brady')
)
console.log(filteredData)

How to verify Array of objects is empty/null/undefined in js

I have a js array of objects as follows:
var person = [{
firstName: "",
lastName: "Doe",
age: 46
}, {
firstName: "John",
lastName: "",
age: 35
}];
How do i find out if at least of the objects in the array, for eg firstName: or lastName: is empty or not? The result of the called function needs only to be true or false.
You can use filter & length like:
const isEmpty = person.filter(x => !x.firstName || !x.lastName).length > 0
Or, using some like:
const isEmpty = person.some(x => !x.firstName || !x.lastName);
EDIT:-
function filterItems(TableData) {
return TableData.filter(function(el) {
return Object.values(el).some(v => !v);
})
}
You can use forEach to iterate over the array and use Object.values to get all the value. Then use indexOf to test if the value matches.Use a variable to save the state
var person = [{
firstName: "",
lastName: "Doe",
age: 46
},
{
firstName: "John",
lastName: "",
age: 35
}
];
function testArray(arr) {
var isEmpty = false
arr.forEach(function(item) {
if (Object.values(item).indexOf("") !== -1) {
isEmpty = true
}
})
return isEmpty;
}
console.log(testArray(person))
If at least one item is null or empty, it returns false
const person = [{
firstName: "",
lastName: "Doe",
age: 46
}, {
firstName: "John",
lastName: "",
age: 35
}];
const allItemsHaveValue = person.map(o => Object.values(o).every(v => v)).every(v => v);
console.log('All items have value: ', allItemsHaveValue);

Loop through an object and create new array

I have an array of objects, I'm trying to loop through them via map function and create an output as follows:
Desired output
dataSet = [
[John, Doe, Sales],
[Jane, Doe, HR],
[Jack, Doe, Manager]
]
My array of objects:
[[object],[object],[object]]
Here is what I have tried so far:
users.map((item) => {
dataSet.push(item.profile.firstName, item.profile.role)
})
However my output:
["John","Jane","Jack"]
How can I push each loop into new array?
Thanks
Actually, you are pretty close. Just make what you want to push an array. Try the following codes:
users.forEach((item) => {
dataSet.push([item.profile.firstName, item.profile.lastName, item.profile.role]);
});
Assuming your original data looks like:
data: [
...
{
profile: {
firstname: "John",
lastname: "Doe",
role: "Sales"
}
},
...
];
You could do this:
var dataSet = data.map((person) => {
let profile = person.profile;
return [
profile.firstname,
profile.lastname,
profile.role
];
});
Hope this helps!
When you are mapping the array of objects you should just return an array with the values you want.
const john = { firstName: 'John', lastName: 'Doe', role: 'Sales' }
const jane = { firstName: 'Jane', lastName: 'Doe', role: 'HR' }
const jack = { firstName: 'Jack', lastName: 'Doe', role: 'Manager' }
const users = [ john, jane, jack ]
const dataSet = users.map(user => ([ user.firstName, user.lastName, user.role ]))
console.log(dataSet)
You can do this in a more generic way by allowing for any number of properties on the object using map, e.g.
dataset = [
{firstName: 'John', lastName: 'Doe', role: 'Sales'},
{firstName: 'Jane', lastName: 'Doe', role: 'HR'},
{firstName: 'Jack', lastName: 'Doe', role: 'Manager'}
];
var result = dataset.map(obj => Object.keys(obj).map(key => obj[key]));
console.log(result)

How to take first and only one object with specific property?

I have array with objects:
[{name:'test', lastname: 'test', gender:'f'},{name:'test1', lastname: 'test1', gender:'m'},{name:'test2', lastname: 'test2', gender:'m'}]
How to get first (and only 1) object from array with genger: 'm'?
You can use find
var ar = [{name:'test', lastname: 'test', gender:'f'},{name:'test1', lastname: 'test1', gender:'m'},{name:'test2', lastname: 'test2', gender:'m'}];
var result = ar.find(function(e) {
return e.gender == 'm';
});
console.log(result)
Loop over your array and check if the item has gender == 'm' in each iteration. Could look like this:
function first_male(data) {
for (var i = 0; i < data.length; i++) {
if (data[i].gender == 'm') {
return data[i];
}
}
}
var data = [
{name:'test', lastname: 'test', gender:'f'},
{name:'test1', lastname: 'test1', gender:'m'},
{name:'test2', lastname: 'test2', gender:'m'}
];
first_male(data); // Object {name: "test1", lastname: "test1", gender: "m"}
You simply have to loop on your array. There is a very similar thread here : Find a value in an array of objects in Javascript
The return instruction will break out of the loop when a corresponding object is found.
You could use Array#find
The find() method returns a value in the array, if an element in the array satisfies the provided testing function. Otherwise undefined is returned.
var array = [{name:'test', lastname: 'test', gender:'f'},{name:'test1', lastname: 'test1', gender:'m'},{name:'test2', lastname: 'test2', gender:'m'}];
console.log(array.find(a => a.gender ==='m'));
If not available, use polyfill. Or
var array = [{name:'test', lastname: 'test', gender:'f'},{name:'test1', lastname: 'test1', gender:'m'},{name:'test2', lastname: 'test2', gender:'m'}],
element;
array.some(function (a) {
if (a.gender === 'm') {
element = a;
return true;
}
});
console.log(element);

Categories