Get values by key in the Array of object - javascript

I've an array which contains the objects including various key and values. I'm going to pick out the certain values from the Array and check if the specific value is included or not in the Array.
function groupByName (contract) {
const { age } = contract;
const groups = [
{name: 'John', age: 30},
{name: 'Jack', age: 33},
{name: 'Tom', age: 40}
...
];
...
}
In order to compare the age in groups array, right now I have to use loop functions and then check one by one.
Like
groups.forEach(g => {
if (g.age === age) {
...
} else {
...
}
});
But I don't like this approach and think there are simple and effective way.
Please help me!

you can use filter to create two sublists
like this
const groups = [
{name: 'John', age: 30},
{name: 'Jack', age: 33},
{name: 'Tom', age: 40}
]
const withAge = age => groups.filter(g => g.age === age)
const withoutAge = age => groups.filter(g => g.age !== age)
const age30 = withAge(30)
const ageNot30 = withoutAge(30)
age30.forEach(g => {
console.log('do some stuff with age 30', g)
})
ageNot30.forEach(g => {
console.log('do some stuff without age 30', g)
})

maybe you can see this function
groups.some(p=>r.age===age)//if there is a object meet the criteria, return true, else return false
or read this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
by the way, if you want to execute the if/else snippet in every loop, maybe you should use forEach

Related

creating Object with different data

I was wondering if there's a way to create an object with changeable data.
Eg:
pearson = {
name: "",
age: 0
}
Can I do something like a loop that each time it changes these 2 variables and assign the whole object with the data into an array, but each time the object will hold the updated data?
Something like:
let pearson = { name: '', age: 20 }
const pearsonsList = [{name: 'dave', age: 20}, {name: 'jessy', age: 30}]
let arr = []
pearsonsList.forEach((e) =>{
pearson.name = e.name
pearson.age = e.age
arr.push(pearson)
})
console.log(arr[0])
/* this what arr[0] holds
{
"name": "jessy",
"age": 30
}*/
how to make arr[0] have a different value than arr[1] where the object data always get overridden ?
The main problem here is your arr is storing the reference to your pearson object, which gets modified each time you set it, even after you push them into your arr.
A solution would be to construct a new object each time before pushing it in.
const pearsonsList = [{name: 'dave', age: 20}, {name: 'jessy', age: 30}]
let arr = []
pearsonsList.forEach((e) =>{
let pearson = { name: '', age: 20 }
pearson.name = e.name
pearson.age = e.age
arr.push(pearson)
})
An optional, and cleaner solution would be to use .map instead of .forEach too
const pearsonsList = [{name: 'dave', age: 20}, {name: 'jessy', age: 30}]
let arr = pearsonsList.map((e) =>{
let pearson = { name: '', age: 20 }
pearson.name = e.name
pearson.age = e.age
return person;
})

check every values in array of object

I have an array of object like this :
const object = [
{name: 'John', age: 15},
{name: 'Victor', age: 15},
{name: 'Emile', age: 14}
]
I need to check if in this array all age are 15. ( just need a boolean for answer )
I need to use something like 'every' method but how with an object ?
You need to use every:
The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value. Array.prototype.every
So the code will be like:
const object = [
{name: 'John', age: 15},
{name: 'Victor', age: 15},
{name: 'Emile', age: 14}
]
const isValid = object.every(item => item.age === 15)
console.log({isValid})
This is js functional ability to test all your elements states.
You just need to extract the property you want to compare
const object = [ {name: 'John', age: 15},{name: 'Victor', age: 15},{name: 'Emile', age: 14}]
let op = object.every(({ age }) => age === 15)
console.log(op)
You can compare the length of the array with length of array of objects with required age.
const object = [
{name: 'John', age: 15},
{name: 'Victor', age: 15},
{name: 'Emile', age: 14}
];
function hasAge(pAge, object) {
return object.length === object.filter(({ age }) => age === pAge).length;
}
console.log(hasAge(15, object));

I am having trouble writing a for...in loop based on a condition in JavaScript [beginner]

I am trying to modify the function to return the count of how many people are 16 or older. I know that I need a for...in loop. That's about as far as I got. Please help.
function countLegalDrivers(people){
}
const examplePeopleArray = [
{ name: 'John', age: 15},
{ name: 'Jane', age: 16},
{ name: 'Jack', age: 17}
];
console.log(countLegalDrivers(examplePeopleArray), '<-- should be 2');
you can do with filter or without filter as well
// with filter
function countLegalDrivers(people) {
return people.filter(p => p.age >= 16).length;
}
// with ordinary for loop
/* function countLegalDrivers(people) {
var count = 0;
for(var i=0;i<people.length;i++){
if(people[i].age>=16){
count++;
}
}
return count;
}
*/
const examplePeopleArray = [
{ name: "John", age: 15 },
{ name: "Jane", age: 16 },
{ name: "Jack", age: 17 }
];
console.log(countLegalDrivers(examplePeopleArray));
function countLegalDrivers(people){
return people.reduce((prev,cur)=>prev+(cur.age>=16?1:0),0);
}
const examplePeopleArray = [
{ name: 'John', age: 15},
{ name: 'Jane', age: 16},
{ name: 'Jack', age: 17}
];
console.log(countLegalDrivers(examplePeopleArray), '<-- should be 2');
The Array.prototype.reduce function is easily to resoleve your problem.
As synchrodynamic points out, this sounds like a homework problem, so I won't post a complete answer here. However, I think it would be fair to tell you that this is the wrong tool for the job. for...in is used to iterate through pairs of keys and values within an object, and per the MDN documentation, it should not be used to iterate through the elements within in an array (which is what you have here). Instead, a simple for loop (or, alternatively, one of the iteration methods mentioned in other comments) should suffice.

How to take an array of objects and create arrays based on property values?

I have an array of objects and trying to take thevalues inside those objects and push them into an array based on the same property value. So for example.
array = [
{name: 'John', age: 12},
{name: 'Lily', age: 22}
]
I have this array of objects and now I want to iterate through it and create arrays with all name values and age values. The array also needs to be the same name as the values. So the result will be.
name = ['John', 'Lily']
age = [12, 22]
How would I be able to do this?
Just map over the array like so:
const array = [
{name: 'John', age: 12},
{name: 'Lily', age: 22}
]
const name = array.map(e => e.name);
const age = array.map(e => e.age);
console.log(name);
console.log(age);
EDIT
If the array has dynamic objects, you can do this:
const array = [
{name: 'John', age: 12},
{name: 'Lily', age: 22}
];
for (var key in array[0]) {
window[key] = array.map(e => e[key]);
}
console.log(name);
console.log(age);

Find element and replace it

I want to make a function (or use library) that will search the array of objects find specific one by its property and replace it with the other object. E.g.:
var a = {name: "Jane", age: 29}
var arr = [{name: "Chris", age: 20}, {name: "Jane", age: 45}]
arr.find(person => { if (a.name === person.name) {person = a})
Is there such a function?
Edit:
It would be nice if there is no matched object in array it would push it to an array that object
I can only think of Array#map
var a = {name: "Jane", age: 29}
var arr = [{name: "Chris", age: 20}, {name: "Jane", age: 45}]
arr = arr.map(function(o){
// if names match, return new object
// otherwise, return original object
return o.name == a.name ? a : o;
});
console.log( arr );
You are probably looking for a wrapper around splice.
Your example would look like this:
arr.forEach((elem, index) => {
if (elem.name !== a.name) return
arr.splice(index, 1, a)
})
You could use the find() method, as such:
var jane = {name: "Jane", age: 29}
var persons = [
{name: "Chris", age: 20},
{name: "Jane", age: 45}
];
function findPerson(person) {
return function(element, index, array) {
if(person.name === element.name) {
array[index] = person;
return true;
}
return false;
}
}
persons.find(findPerson(jane));
This would replace the matched person if found and else returns undefined. So you could check if undefined is returned and add the person afterwards.
Since you want to modify the original array, you can use array#forEach(), just iterate through the array and replace the object which matches your a object name.
var a = {name: "Jane", age: 29}
var arr = [{name: "Chris", age: 20}, {name: "Jane", age: 45}]
arr.forEach((person,index) => {
if (a.name === person.name)
arr[index] = a;
})
console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Categories