Finding a property value in an array of object based on another property value - arrays

I have the following array
const arrayOfObject = [{
name: 'Mike',
age: '38',
}, {
name: 'Russell',
age: '42',
}, {
name: 'John',
age: '26',
}, ];
and I want to find the age of 'Russell' for instance.
If I use .find() I manage to get the whole object
const employeeAge = arrayOfObject.find((item) => item.name === 'Russell')
Is it possible to do it in one line?

Related

Filtering out a name starting with letter 'P' from Array of objects using typescript

Here's my code:
const names = [
{name:'Finn',age: 23},
{name:'Presten',age: 24},
{name:'Pearl',age: 21},
{name:'Tim',age: 22},
{name:'Jade',age: 25},
{name:'Princess',age: 23},
]
const filterName = names.filter(function(nameWithOutC: {name: string, age: number}): boolean {
return nameWithOutP.book !== 'P'
})
console.log('Filtering out a name starting with letter P')
console.log(filterName)
I am trying to figure out how can able to filter out the names starting with the letter "P".
You can use something like this to get rid of strings starting with the letter "P":
bookstore.filter((name, age) => !name.startsWith("P"))
Or this to only keep strings with the starting letter "P":
bookstore.filter((name, age) => name.startsWith("P"))
by placing search you can search for any word in the string, of course using the filter method, you can also negate it:
!name.search("P")
const names = [
{ name: "Finn", age: 23 },
{ name: "Presten", age: 24 },
{ name: "Pearl", age: 21 },
{ name: "Tim", age: 22 },
{ name: "Jade", age: 25 },
{ name: "Princess", age: 23 }
];
const filterName = names.filter(({ name }) => name.search("P"));
console.log("Filtering out a name starting with letter P");
console.log(filterName);

How to concatenate fields in Tabulator, while retaining header search?

We need to be able to concatenate multiple fields into a single Tabulator column. This in of itself is easy enough, but we want to also be able to use the column search function to search for ANY of the values that have been inserted.
Using the mutate function of course breaks Tabulators ability to distinguish one original value from any other.
We've got around this by having Tabulator modify our data source dynamically (dynamically regenerating the datasource query) but this is of course not the ideal solution.
I'm wondering if anyone else has run into this and found a built-in solution?
EG: Column "NAME" contains the concatenation of "firstname, lastname". We need to be able to use the column filter to search either the firstname or lastname, but through mutation/concatenation, we are now forced to search firstname first instead of lastname.
You could use a custom filter function to perform the search. In the below example, I have used the header filter, but it could be an external search input as well. My example has firstName and lastName columns concatenated as Lastname, Firstname in the name column. By using the headerFilterFunc column definition property, you could return search results that match either first name or last name:
const dataSet1 = [
{ firstName: 'Billy', lastName: 'Bob', age: '12', gender: 'male' },
{ firstName: 'Mary', lastName: 'May', age: '1', gender: 'female' },
{ firstName: 'Christine', lastName: 'Lobowski', age: '42', gender: 'female' },
{ firstName: 'Brendon', lastName: 'Philips', age: '25', gender: 'male' },
{ firstName: 'Margret', lastName: 'Marmajuke', age: '76', gender: 'female' }
]
const table = new Tabulator('#table', {
data: dataSet1,
columns: [
{
title: 'Name',
field: 'name',
mutator: (value, data) => data.lastName + ', ' + data.firstName,
headerFilter: 'input',
headerFilterFunc: (headerValue, rowValue, rowData, filterParams) => {
let filterValue = headerValue.toUpperCase()
let firstName = rowData.firstName.toUpperCase()
let lastName = rowData.lastName.toUpperCase()
return firstName.includes(filterValue) || lastName.includes(filterValue)
}
},
{ title: 'Age', field: 'age' },
{ title: 'Gender', field: 'gender' }
]
})
<link href="https://unpkg.com/tabulator-tables#5.1.8/dist/css/tabulator.min.css" rel="stylesheet">
<script type="text/javascript" src="https://unpkg.com/tabulator-tables#5.1.8/dist/js/tabulator.min.js"></script>
<div id="table"></div>

How do I put an object inside another object based on the same key?

I am working with Reactjs and my data looks like this:
const this.state.singlePost = [{
name: 'Johnny',
age: 20,
birthPlace: 'Germany'
},
{
name: 'Samuel',
age: 22,
birthPlace: 'France'
}
]
let this.state.post = [{
email: 'john#gm.co',
number: 4567887654
},
{
email: 'samuel#gm.co',
number: 0987655881
},
]
I want to make something like this:
let editedPost = [{
name: 'Johnny',
age: 20,
birthPlace: 'Germany',
email: 'john#gm.co',
number: 4567887654
},
{
name: 'Samuel',
age: 22,
birthPlace: 'France',
email: 'samuel#gm.co',
number: 0987655881
}
]
It might be a stupid question, but I got stuck for a few hours on this, Could somebody help me please? I have 5 items in this.state.singlePost and 10 items in this.state.post. How do I put the stuff in this.state.singlePost into this.state.post just like the way I did in editedPost?
In theory, you would have a common key between the two objects that you would be able to merge on as without you will be relying on matching the index of objects.
let post = [
{email: 'john#gm.co',
number: 4567887654},
{email: 'samuel#gm.co',
number: 987655881}
]
let singlePost = [
{name: 'Johnny', age: 20, birthPlace: 'Germany'},
{name: 'Samuel', age: 22, birthPlace: 'France'}
]
let newList = post.map((item, i) => ({...item, ...singlePost[i]}))
console.log(newList)
Output:
[
{
email:"john#gm.co",
number:4567887654,
name:"Johnny",
age:20,
birthPlace:"Germany"
},
{
email:"samuel#gm.co",
number:987655881,
name:"Samuel",
age:22,
birthPlace:"France"
}
]
There is many ways to do this in Javascript. The way I chose prevents mutation of data, which may be something you are concerned with when using React.

How to filter all the fields in react?

How to filter all the fields in react?
I have written a code which only filters specified fields.
let filteredContacts=this.props.contacts.filter(
(contact)=>{
return contact.name.indexOf(this.state.search)!==-1;
}
);
the above code only returns filtered names...but i want to filter name,age,city work.
this is the data file:
export default function(){
return [{
key: 1,
name: 'Steve',
city: 'Paris',
}, {
key: 2,
name: 'Tim',
city: 'London',
}, {
key: 3,
name: 'Stella',
city: 'Bankok',
}, {
key: 4,
name: 'John',
city: 'Paris',
}];
}
i want to create a search bar which which filters all the fields suppose if i search john then the list of john should be displayed and if i search paris then all the entries which have paris should be displayed..So the code which i have written only searches for name as i have specified name..i want to search the inputed data to search all the fields.
The filter criteria can be the indexOf on Object.values() like below but it will only give a complete match
var data = [{
key: 1,
name: 'Steve',
city: 'Paris',
}, {
key: 2,
name: 'Tim',
city: 'London',
}, {
key: 3,
name: 'Stella',
city: 'Bankok',
}, {
key: 4,
name: 'John',
city: 'Paris',
}];
var value = 'Paris'
var newData = data.filter((obj) => {
return Object.values(obj).indexOf(value) > -1
})
console.log(newData)
Well, I fastly tried, do a loop on your keys. Maybe there's a more elegant way.
let filteredContacts=this.props.contacts.filter(
(contact)=>{
var found = false;
Object.keys(contact).map(function(key, index) {
if (contact[key].indexOf(this.state.search) >= 0)
found = true;
}
return found;
}
);

Querying array of objects in typescript

I have an array of JSON objects
array = [{name: "will", age: "18"}
{name: "Elliott", age: "21"}
]
Is there a way to get the "age" for any given "name" (as you would do with a SQL statement when querying a database?
Yes.
let array = [
{ name: "will", age: "18"},
{ name: "john", age: "18"},
{ name: "elliott", age: "21"}
]
array.filter((e) => { return e.name === 'john' })
Result
[ { name: 'john', age: '18' } ]
let queryName = 'will';
array.forEach((obj) => {
if (obj.name === queryName) {
console.log(obj.name, obj.age); // will 18
}
});

Resources