I'd like to create a function that iterates through an array containing separate objects with name, surname and age properties. The function should take a parameter "name" and return the name, surname and age in the console.
How would I do this? I've looked at some other questions but can't seem to figure out how to do it. I've created this so far...
var people = [
{ name: "Sue", surname: "Beckett", age: 50},
{ name: "Bill", surname: "Borough", age: 44},
{ name: "Janet", surname: "Jupp", age: 23},
{ name: "Peter", surname: "Pepper", age: 21},
{ name: "Samantha", surname: "Salad", age: 17}
];
function person(name) {
// code here
}
person(sue)
Simply use Array#find() method like this:
function person(name) {
return people.find(function(p) {
return p.name == name;
});
}
console.log(person("Samantha"));
Demo:
var people = [{
name: "Sue",
surname: "Beckett",
age: 50
},
{
name: "Bill",
surname: "Borough",
age: 44
},
{
name: "Janet",
surname: "Jupp",
age: 23
},
{
name: "Peter",
surname: "Pepper",
age: 21
},
{
name: "Samantha",
surname: "Salad",
age: 17
}
];
function person(name) {
return people.find(function(p) {
return p.name == name;
});
}
console.log(person("Samantha"));
console.log(Object.values(person("Samantha")));
Note:
Make sure you pass the name as a string when you call your method, passing just sue without "" will assume you have a variable called sue.
Note that you can use Object.values() to show only the values of
the object properties, instead of the whole object.
Simply write :
console.log(Object.values(person("Samantha")));
var people = [
{ name: "Sue", surname: "Beckett", age: 50},
{ name: "Bill", surname: "Borough", age: 44},
{ name: "Janet", surname: "Jupp", age: 23},
{ name: "Peter", surname: "Pepper", age: 21},
{ name: "Samantha", surname: "Salad", age: 17}
];
function person(name) {
for (var key in people) {
var person = people[key];
if (name === person.name) {
console.log(person);
}
}
}
person("Sue"); // string always needs quotes: " or ' character
You could filter the array by checking the lower case value of name property and name variable.
function person(name) {
people
.filter(o => o.name.toLowerCase() === name.toLowerCase())
.forEach(({ name, surname, age}) => {
console.log('name:', name);
console.log('suname:', surname);
console.log('age:', age);
});
}
var people = [{ name: "Sue", surname: "Beckett", age: 50 }, { name: "Bill", surname: "Borough", age: 44 }, { name: "Janet", surname: "Jupp", age: 23 }, { name: "Peter", surname: "Pepper", age: 21 }, { name: "Samantha", surname: "Salad", age: 17 }];
person('sue');
Using filter:
var people = [
{ name: "Sue", surname: "Beckett", age: 50},
{ name: "Bill", surname: "Borough", age: 44},
{ name: "Janet", surname: "Jupp", age: 23},
{ name: "Peter", surname: "Pepper", age: 21},
{ name: "Samantha", surname: "Salad", age: 17}
];
function person(personName) {
var user = people.filter(function (user) {
return (user.name.toLowerCase() == personName.toLowerCase());
});
return user[0] !== undefined ? user[0] : 'not found';
}
console.log(person('sue'));
var people = [
{ name: "Sue", surname: "Beckett", age: 50},
{ name: "Bill", surname: "Borough", age: 44},
{ name: "Janet", surname: "Jupp", age: 23},
{ name: "Peter", surname: "Pepper", age: 21},
{ name: "Samantha", surname: "Salad", age: 17}
];
function person(name) {
people.map((data,index)=>{
if(data.name == name)
{
console.log(data.name);
console.log(data.surname);
console.log(data.age);
return;
}
})
}
person("Sue");
Related
This question already has answers here:
Is Chrome’s JavaScript console lazy about evaluating objects?
(7 answers)
Closed 9 months ago.
Edit: This seems related to the way the chrome console handles object evaluation as noted by
jsN00b
original here
I'm sorting an array by name and then by age, logging the array three times:
Once right after initialization,
second and third time is after sorting the array by name and then age respectively.
The first console.log() call however, prints the array in its sorted state, but what I expected to have is the array in it's unsorted state.
Not sure if this is related to the way JavaScript handles array in memory or is is it a bug?
Code:
function byField(field) {
return (objA, objB) => (objA[field] > objB[field] ? 1 : -1);
}
let users = [
{ name: "John", age: 20, surname: "Johnson" },
{ name: "Pete", age: 18, surname: "Peterson" },
{ name: "Ann", age: 19, surname: "Hathaway" },
];
console.log(users);
users.sort(byField("name"));
console.log(users);
users.sort(byField("age"));
console.log(users);
.as-console-wrapper { max-height: 100% !important; top: 0 }
Expected output:
//unsorted
[
{ name: "John", age: 20, surname: "Johnson" },
{ name: "Pete", age: 18, surname: "Peterson" },
{ name: "Ann", age: 19, surname: "Hathaway" },
];
//by name
[
{ name: "Ann", age: 19, surname: "Hathaway" },
{ name: "John", age: 20, surname: "Johnson" },
{ name: "Pete", age: 18, surname: "Peterson" },
];
//by age
[
{ name: "Pete", age: 18, surname: "Peterson" },
{ name: "Ann", age: 19, surname: "Hathaway" },
{ name: "John", age: 20, surname: "Johnson" },
];
Actual Output:
//unsorted
[
{ name: "Pete", age: 18, surname: "Peterson" },
{ name: "Ann", age: 19, surname: "Hathaway" },
{ name: "John", age: 20, surname: "Johnson" },
];
//by name
[
{ name: "Pete", age: 18, surname: "Peterson" },
{ name: "Ann", age: 19, surname: "Hathaway" },
{ name: "John", age: 20, surname: "Johnson" },
];
//by age
[
{ name: "Pete", age: 18, surname: "Peterson" },
{ name: "Ann", age: 19, surname: "Hathaway" },
{ name: "John", age: 20, surname: "Johnson" },
];
Method Array.prototype.sort does mutate your initial array. For fix this problem you need to create copy of array and then sort this copy.
It is like follow example:
[...users].sort(byField("name"));
myData: {
name: "",
surname: "",
family: {
mother: "",
father: ""
},
age: ""
}
responseData: {
name: "John",
surname: "Doe",
family: {
mother: "Jennifer"
}
phone: "0123456789",
weight: 88
}
const pick = require('lodash/pick')
const formKeys = Object.keys(this.myData)
this.myData = pick(this.responseData, formKeys)
myData Output:
{
name: "John",
surname: "Doe",
family: {
mother: "Jennifer"
}
}
I want it to be like this
{
name: "John",
surname: "Doe",
family: {
mother: "Jennifer",
father: ""
},
age: ""
}
myData fields should never be corrupted, if there is a key that does not match, keep that field as it is in the myData.
I want deeper match.
I used lodash(pick) for this. How if it is done with lodash? Or how can I do it any other way?
You can merge like below.
const myData = {
name: "",
surname: "",
family: {
mother: "",
father: "",
},
age: "",
};
const responseData = {
name: "John",
surname: "Doe",
phone: "0123456789",
weight: 88,
};
const merge = (obj1, obj2) => {
const merged = { ...obj1 };
Object.keys(obj1).forEach((key) => {
merged[key] = obj2[key] ?? obj1[key];
});
return merged;
};
console.log(merge(myData, responseData));
I'm looking for a simple methodology to merge the Array of the nested object into an array of the same object
Input:
const data=[
{ id: 123, name: "dave", age: 23 , address:{city:"chennai", zipcode:600001}},
{ id: 456, name: "chris", age: 23, address:{city:"cbe", zipcode:600002} },
{ id: 789, name: "bob", age: 23, address:{city:"tiruppur", zipcode:600003}},
{ id: 101, name: "tom", age: 23, address:{city:"erode", zipcode:600004} },
{ id: 102, name: "tim", age: 23, address:{city:"selam", zipcode:600005} }
]
Needed Output:
{ id: 123, name: "dave", age: 23, city:"chennai", zipcode:600001},
{ id: 456, name: "chris", age: 23, city:"cbe", zipcode:600002},
{ id: 789, name: "bob", age: 23, city:"tiruppur", zipcode:600003},
{ id: 101, name: "tom", age: 23, city:"erode", zipcode:600004},
{ id: 102, name: "tim", age: 23, city:"selam", zipcode:600005}
]
Use a combination of destructuring and spread syntax:
const data=[{ id: 123, name: "dave", age: 23 , address:{city:"chennai", zipcode:600001}},{ id: 456, name: "chris", age: 23, address:{city:"cbe", zipcode:600002} },{ id: 789, name: "bob", age: 23, address:{city:"tiruppur", zipcode:600003}},{ id: 101, name: "tom", age: 23, address:{city:"erode", zipcode:600004} },{ id: 102, name: "tim", age: 23, address:{city:"selam", zipcode:600005} }];
const result = data.map(({address, ...rest}) => ({...rest, ...address}));
console.log(result);
You can use Object.entries to extract each property and its value in the address property and assign it to the parent object, then delete the address property.
const data=[{id:123,name:"dave",age:23,address:{city:"chennai",zipcode:600001}},{id:456,name:"chris",age:23,address:{city:"cbe",zipcode:600002}},{id:789,name:"bob",age:23,address:{city:"tiruppur",zipcode:600003}},{id:101,name:"tom",age:23,address:{city:"erode",zipcode:600004}},{id:102,name:"tim",age:23,address:{city:"selam",zipcode:600005}}];
const result = data.map(e => (Object.entries(e.address).forEach(f => e[f[0]] = f[1]), delete e.address, e))
console.log(result)
let data = [
{ id: 123, name: "dave", age: 23, address: { city: "chennai", zipcode: 600001 } },
{ id: 456, name: "chris", age: 23, address: { city: "cbe", zipcode: 600002 } },
{ id: 789, name: "bob", age: 23, address: { city: "tiruppur", zipcode: 600003 } },
{ id: 101, name: "tom", age: 23, address: { city: "erode", zipcode: 600004 } },
{ id: 102, name: "tim", age: 23, address: { city: "selam", zipcode: 600005 } }
]
data = data.map((node) => ({ id: node.id, name: node.name, age: node.age, city: node.address.city, zipcode: node.address.zipcode }))
console.log(data)
const data=[
{ id: 123, name: "dave", age: 23 , address:{city:"chennai", zipcode:600001}},
{ id: 456, name: "chris", age: 23, address:{city:"cbe", zipcode:600002} },
{ id: 789, name: "bob", age: 23, address:{city:"tiruppur", zipcode:600003}},
{ id: 101, name: "tom", age: 23, address:{city:"erode", zipcode:600004} },
{ id: 102, name: "tim", age: 23, address:{city:"selam", zipcode:600005} }
];
const result = data.map(item => ({id: item.id, name: item.name, age: item.age, ...item.address}));
console.log(result);
let a = [{ name: "ben", age: 25 }, { name: "jeffrey", age: 10 },{ name: "daniel", age: 20 }]
let case1 = { name: "ben", age: 10 }
let case2={ name: "jack", age: 30 }
case1:
i expect the result to be
[{ name: "ben", age: 10 }, { name: "jeffrey", age: 10 },{ name: "daniel", age: 20 }]
where "ben" is existing so it replaces age to 10
case2:
i expect the result to be
[{ name: "ben", age: 25 }, { name: "jeffrey", age: 10 },{ name: "daniel", age: 20 },{ name: "jack", age: 30 }]
where "jack" is not there in the array so it adds to the array
how to write a function which does this functionality
Yours is a good case for Array.prototype.findIndex (MDN), which is like Array.prototype.find but returns the found index instead of the item.
let a = [{ name: "ben", age: 25 }, { name: "jeffrey", age: 10 },{ name: "daniel", age: 20 }]
let case1 = { name: "ben", age: 10 }
let case2 = { name: "jack", age: 30 }
const arrayUpsert = function (array, object) {
const objectIndex = array.findIndex(item => item.name == object.name)
if (objectIndex == -1) {
array.push(object)
} else {
array[objectIndex] = { ...array[objectIndex], ...object }
}
return array
}
console.log(arrayUpsert(a, case1))
console.log(arrayUpsert(a, case2))
/* [
{ name: 'ben', age: 10 },
{ name: 'jeffrey', age: 10 },
{ name: 'daniel', age: 20 }
]
[
{ name: 'ben', age: 10 },
{ name: 'jeffrey', age: 10 },
{ name: 'daniel', age: 20 },
{ name: 'jack', age: 30 }
] */
Can be done with a for loop as well.
function untitled(original, newObj) {
for (let index = 0; index < original.length; index++) {
if (original.name && newObj.name === a[index].name) {
original[index] = {...newObj};
console.log(original); return;
}
}
original.push(newObj); console.log(original);
}
let a = [{ name: "ben", age: 25 }, { name: "jeffrey", age: 10 },{ name: "daniel", age: 20 }]
let case1 = { name: "ben", age: 10 }
let case2 = { name: "jack", age: 30 }
untitled(a, case1);
untitled(a, case2);
I'm using ramda library in my solution:-
Check whether the key exist in any of the object in array by
idx = R.findIndex(R.propEq('name', 'ben'), a). If idx<0 then we can directly push the object else go to the next step.
We have the index(idx), we just have to do a[idx].age="--".
My question is extension to this question javascript filter array multiple conditions
from that question if filter object is
{address: 'England', name: 'Mark'};
and array is
var users = [{
name: 'John',
email: 'johnson#mail.com',
age: 25,
address: 'USA'
},
{
name: 'Tom',
email: 'tom#mail.com',
age: 35,
address: 'England'
},
{
name: 'Mark',
email: 'mark#mail.com',
age: 28,
address: 'England'
}
];
so the answer is
[
{
"name": "Mark",
"email": "mark#mail.com",
"age": 28,
"address": "England"
}
]
which is absolutely fine but my question is array has to be filtered for the filter object properties value
for example my filter object will be {address: 'England', name: ''} now this has to filter the array for all names and address England
You'd use filter on users and every on the filter object's entries
const filter = {address: 'England', name: 'Mark'};
const res = users.filter(user =>
Object.entries(filter)
.every(([k,v]) => v === '' || user[k] === v)
);
console.log(res);
<script>
var users = [{
name: 'John',
email: 'johnson#mail.com',
age: 25,
address: 'USA'
},
{
name: 'Tom',
email: 'tom#mail.com',
age: 35,
address: 'England'
},
{
name: 'Mark',
email: 'mark#mail.com',
age: 28,
address: 'England'
}
];
</script>
From the example in the post you mention, just continue if the filter is blank
var filter = {address: 'England', name: ''}
var users = [{
name: 'John',
email: 'johnson#mail.com',
age: 25,
address: 'USA'
},
{
name: 'Tom',
email: 'tom#mail.com',
age: 35,
address: 'England'
},
{
name: 'Mark',
email: 'mark#mail.com',
age: 28,
address: 'England'
}
];
users = users.filter(function(item) {
for (var key in filter) {
if (filter[key] == "") continue; // added this:
if (item[key] === undefined || item[key] != filter[key])
return false;
}
return true;
});
console.log(users)
You can use a combination of filter and every with some ternary logic to determine if the filter value is empty to get all.
var users = [{
name: 'John',
email: 'johnson#mail.com',
age: 25,
address: 'USA'
},
{
name: 'Tom',
email: 'tom#mail.com',
age: 35,
address: 'England'
},
{
name: 'Mark',
email: 'mark#mail.com',
age: 28,
address: 'England'
}
];
var filter1 = {address: 'England', name: 'Mark'};
var filter2 = {address: 'England', name: ''};
function findResults(input, filterObj){
return input.filter(
item => Object.keys(filterObj)
.every(r => filterObj[r].length
? item[r] == filterObj[r]
: true)
)
}
console.log('with address and name', findResults(users,filter1));
console.log('with address only', findResults(users,filter2));
If I understand your question correctly you need following output.
If this what you are looking for Array.filter should suffice your use case.
Take a look at the code sandbox where I have created a function filterByObj which takes arr, filterObj as arguments and returns given output for { address: "England", name: "" }
You need you filter for this case.
var filter1 = {
address: 'England',
name: 'Mark'
};
var filter2 = {
address: 'England',
name: ''
};
var users = [
{
name: 'John',
email: 'johnson#mail.com',
age: 25,
address: 'USA'
},
{
name: 'Tom',
email: 'tom#mail.com',
age: 35,
address: 'England'
},
{
name: 'Mark',
email: 'mark#mail.com',
age: 28,
address: 'England'
}
];
function filterUser(arr, obj) {
return arr.filter(function(item) {
return (
(obj.address === '' || item.address === obj.address) &&
(obj.name === '' || item.name === obj.name)
);
});
}
console.log(filterUser(users, filter1));
console.log(filterUser(users, filter2));