Getting objects in an array that has a specific property - arrays

Alright, so I am trying to make an ArtistPage, and I need to put all the albums by that artist, on the page. I put a property called artistName in each album as a way of kinda referencing it but idk if that is the correct practice.
This is the results of a variable called getAlbums that i have in the code that returns an array of objects, which are all the albums in the 'database' -->
[
{name: "The Cool", genre: "Hip-Hop", artistName: "Lupe Fiasco", year: "2006", isExplicit: "true", …}
{name: "Food & Liquor", artistName: "Lupe Fiasco", genre: "Hip-Hop", year: "2006", isExplicit: "true", …}
{name: "Flume", artistName: "Flume", genre: "Electronic", year: "2012", isExplicit: "true", …}
{name: "Skin", artistName: "Flume", isExplicit: "true", genre: "Electronic", year: "2016", …}
{name: "Hybrid Theory", artistName: "Linkin Park", isExplicit: "true", genre: "Nu-Metal", year: "2000", …}
{name: "Views", artistName: "Drake", genre: "Hip-Hop", year: "2016", isExplicit: "true", …}
{name: "2014 Forest Hills Drive", artistName: "J.Cole", isExplicit: "true", genre: "Hip-Hop", year: "2014", …}
{name: "Marshal Matthers LP", artistName: "Eminem", isExplicit: "true", genre: "Hip-Hop", year: "2000", …}
]
I'm using a function to try and loop though all the properties but its wrong ahh.
It only returns one album
getAlbumsByArtist(artistName: any) {
for (var i = 0; i <= this.getAlbums.length - 1; i++) {
if (this.getAlbums[i].artistName === this.artistName) {
return this.getAlbums[i];
}
}
}
So if I wanted to retrieve ALL objects that has the property "artistName: Flume" in this array, how would I go about doing that?

You can use Array.prototype.filter():
getAlbumsByArtist (artistName: any) {
return this.getAlbums.filter(album => album.artistName === artistName);
}
You could even define a generic method to search by any property like this:
getAlbumsByProperty (property: string, value: any) {
return this.getAlbums.filter(album => album[property] === value);
}
and call that like database.getAlbumsByProperty('artistName', 'Flume')

You can use HigherOrder functions in this case.
var albums=array.filter(album=> {
if(album.artistName==='Flume') {
return album;
}
})
console.log("ans", albums);
Working Fiddle:
https://jsfiddle.net/241wkzph/

Related

MongoDB - How to retrieve only one specific document from a collection

I have created a database called "Cars" and a collection inside it as, "Cars_info". I have inserted 8 documents inside it as follows.
db.Cars_info.insertMany([
{ car_id: "c1", Company: "Toyota", Model: "Aqua", Year: 2020, Price_in_usd: 25000, Category: "High-end", Country: "Japan" },
{ car_id: "c2", Company: "Toyota", Model: "Premio", Year: 2019, Price_in_usd: 35000, Category: "High-end", Country: "Japan" },
{ car_id: "c3", Company: "Audi", Model: "A6", Year: 2020, Price_in_usd: 55000, Category: "High-end", Country: "Germany" },
{ car_id: "c4", Company: "Tata", Model: "Nano", Year: 2015, Price_in_usd: 10000, Category: "Low-end", Country: "India" },
{ car_id: "c5", Company: "Volkswagen", Model: "Taos", Year: 2022, Price_in_usd: 35000, Category: "High-end", Country: "Germany" },
{ car_id: "c6", Company: "Ford", Model: "Figo", Year: 2019, Price_in_usd: 26000, Category: "High-end", Country: "America" },
{ car_id: "c7", Company: "Mahindra", Model: "Thar", Year: 2018, Price_in_usd: 18000, Category: "Low-end", Country: "India" },
{ car_id: "c8", Company: "Honda", Model: "Vezel", Year: 2015, Price_in_usd: 33000, Category: "High-end", Country: "Japan" }
])
Here I want to retrieve only the third document from the collection. But without matching any field value. like,
db.Cars_info.find({"car_id":"c3"}).pretty()
Is there any way to do this?
You need .skip() and .limit().
Take the document by starting index: 2 and with only 1 document, which is the third document.
Update: Thanks and credit to #Wernfried for pointing out, you need .sort() to guarantee to get the nth of the document. For your scenario, you have to sort by car_id.
Sort Consistency
MongoDB does not store documents in a collection in a particular order. When sorting on a field that contains duplicate values, documents containing those values may be returned in any order.
db.Cars_info.find()
.sort({ "car_id": 1 })
.skip(2)
.limit(1)

Push an object from an array into another array javascript

I am having an issue with pushing an object into an array. I am fetching an array of objects from a local .json file. I am trying to create a function that pushes the given object into an array, so I can use it later on.
This is how I am receiving my object.
{id: 3176, name: "Matthias Ginter", position: "Defender", dateOfBirth: "1994-01-03T00:00:00Z", countryOfBirth: "Germany", …}
countryOfBirth: "Germany"
dateOfBirth: "1994-01-03T00:00:00Z"
id: 3176
name: "Matthias Ginter"
nationality: "Germany"
position: "Defender"
role: "PLAYER"
__proto__: Object
My code in React:
{data.map(
(player) => (
player.position == null ? (player.position = "Coach") : null,
(
<PlayerCard
name={player.name}
position={player.position}
dateOfBirth={player.dateOfBirth}
nationality={player.nationality}
id={player.id}
handleClick={() => selectedPlayers.push(player)}
/>
)
)
)}
and the array I am trying to push into:
let selectedPlayers = [
{
id: 3176,
name: "Matthias Ginter",
position: "Defender",
dateOfBirth: "1994-01-03T00:00:00Z",
countryOfBirth: "Germany",
nationality: "Germany",
role: "PLAYER",
},
{
id: 3176,
name: "Mat Giensien",
position: "Defender",
dateOfBirth: "1994-01-03T00:00:00Z",
countryOfBirth: "Germany",
nationality: "Germany",
role: "PLAYER",
},
];
if I do handleClick = {() => {console.log(player)}} I get the object as shown above. What am I missing ?!
I read through all the topics here in SO but couldn't find a solution that would work for me. I have tried all the reccomended ways in the other topics and they still don't work for me.
Please, halp meeeeh :)
{data.map(player => {
return (
<PlayerCard
name={player.name}
position={player.position ? "Coach" : null}
dateOfBirth={player.dateOfBirth}
nationality={player.nationality}
id={player.id}
handleClick={() => selectedPlayers.push(player)}
/>
)
)}
Try this:
let selectedPlayers = [
{
id: 3176,
name: "Matthias Ginter",
position: "Defender",
dateOfBirth: "1994-01-03T00:00:00Z",
countryOfBirth: "Germany",
nationality: "Germany",
role: "PLAYER"
},
{
id: 3176,
name: "Mat Giensien",
position: "Defender",
dateOfBirth: "1994-01-03T00:00:00Z",
countryOfBirth: "Germany",
nationality: "Germany",
role: "PLAYER"
}
];
let newData = {id: 9999, name: "bob jones", position: "goalkepper", dateOfBirth: "2020-01-03T00:00:00Z", nationality: "Spain", role: "MANAGER"}
selectedPlayers.push(newData);
console.log( selectedPlayers );
You might have to mess around with the formatting of the recevied object and the object you're pushing into to make iy work properly. But, if you're in control of the code and the JSON file then that shouldn't be an issue...

CheckboxGroupInput not rendering after save in react-admin

I'm new to react and react-admin and I have a problem with CheckboxGroupInput or with any input of array type.
I have a form, this is the code:
export const MoviesCreate = (props) => (
<Create {...props}>
<SimpleForm>
<TextInput source="name" validate={[required()]} />
<TextInput source="actors" validate={[required()]} />
<TextInput source="year" validate={[required()]} />
<CheckboxGroupInput source="gender" validate={[required()]} choices={[
{ id: 'Action', name: 'Action' },
{ id: 'Adventure', name: 'Adventure' },
{ id: 'Animation', name: 'Animation' },
{ id: 'Biography', name: 'Biography' },
]} />
</SimpleForm>
</Create>
);
So when I want to create a new item, after I hit the save button I got this error:
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
I think the problem is that the response from REST API is not correctly returned but I don't know what is the correct format for that. These are the responses that I tried to returned from REST API but nothing works:
1.
{id: 42, name: "test", year: "1234", actors: "asd", gender: "Adventure,Animation"}
2.
{id: 43, name: "Black Friday", year: "1234", actors: "asd", gender: ["Animation", "Adventure"]}
3.
{id: 43, name: "Black Friday", year: "1234", actors: "asd", gender: [{id: "Adventure", name: "Adventure"}, {id: "Animation", name: "Animation"}]}
4.
{id: 43, name: "Black Friday", year: "1234", actors: "asd", gender: {id: "Animation", name: "Animation"}}
I have the same problem with ArrayInput or AutocompleteArrayInput...
Can anyone help me with this problem and tell me what am I doing wrong?
If you want to let the user choose multiple values among a list of possible values by showing them all,<CheckboxGroupInput> is the right component. Set the choices attribute to determine the options (with id, name tuples):
Description
<CheckboxGroupInput source="category" choices={[
{ id: 'programming', name: 'Programming' },
{ id: 'lifestyle', name: 'Lifestyle' },
{ id: 'photography', name: 'Photography' },
]} />
So,the response from REST API should be like:option 3
{id: 43, name: "Black Friday", year: "1234", actors: "asd", gender: [{id: "Adventure", name: "Adventure"}, {id: "Animation", name: "Animation"}]}

Ruby: using an array of hashes to select values from another array of hashes

Say I have two arrays of hashes:
array_1 = [{name: "Dale Cooper", role: "author"},
{name: "Lucy Moran", role: "author"},
{name: "Harry Truman", role: "author"}]
array_2 = [{author: "Lucy Moran", title: "Lorem"},
{author: "Bobby Briggs", title: "Ipsum"},
{author: "Harry Truman", title: "Dolor"}]
How would I go about selecting from array_2 just the hashes from authors that are in array_1? Preferably, the result would be this:
array_3 = [{author: "Lucy Moran", title: "Lorem"},
{author: "Harry Truman", title: "Dolor"}]
You could save all the array_1 names in a set in order to select hashes from array_2 :
require 'set'
array_1 = [{ name: 'Dale Cooper', role: 'author' },
{ name: 'Lucy Moran', role: 'author' },
{ name: 'Harry Truman', role: 'author' }]
array_2 = [{ author: 'Lucy Moran', title: 'Lorem' },
{ author: 'Bobby Briggs', title: 'Ipsum' },
{ author: 'Harry Truman', title: 'Dolor' }]
authors = Set.new(array_1.map{ |h| h[:name] })
array_3 = array_2.select{ |h| authors.include?(h[:author]) }
# [{:author=>"Lucy Moran", :title=>"Lorem"},
# {:author=>"Harry Truman", :title=>"Dolor"}]

Mongoose sort and get non repeated values

im new in all NodeJS/MongoDB/Mongoose tecnologies, and im trying to get non repeated values from an array, and im sorting the data by two values; location and created_at.
This is the code
Temperature.find().sort({'location': -1,'created_at': -1}).exec(function(err, results){
res.json(results);
});
How can i get the first non repeated value from the array?
This is the array:
[ {
temperature: '24',
humidity: '15',
location: 'Camara4',
created_at: 2017-01-24T21:40:21.552Z
},
{
temperature: '23',
humidity: '15',
location: 'Camara4',
created_at: 2017-01-24T01:18:26.328Z
},
{
temperature: '15',
humidity: '12',
location: 'Camara3',
created_at: 2017-01-26T18:53:34.447Z,
},
{
temperature: '36',
humidity: '11',
location: 'Camara3',
created_at: 2017-01-24T21:41:07.094Z,
},
{
temperature: '35',
humidity: '11',
location: 'Camara3',
created_at: 2017-01-24T21:41:03.092Z,
}
]
and i expect:
[ {
temperature: '24',
humidity: '15',
location: 'Camara4',
created_at: 2017-01-24T21:40:21.552Z
},
{
temperature: '15',
humidity: '12',
location: 'Camara3',
created_at: 2017-01-26T18:53:34.447Z,
},
]
You'll need to use aggregation framework.
$group on location key with $first operator to pick the first value from the sorted order in each group.
Temperature.aggregate({
"$sort": {
'location': -1,
'created_at': -1
}
}, {
$group: {
"_id": "$location",
"result": {
"$first": "$$ROOT"
}
}
}).exec(function(err, results) {
res.json(results);
});
Output:
{
"_id" : "Camara4",
"result" : {
"temperature" : "24",
"humidity" : "15",
"location" : "Camara4",
"created_at" : ISODate("2017-01-24T21:40:21.552Z")
}
}
{
"_id" : "Camara3",
"result" : {
"temperature" : "15",
"humidity" : "12",
"location" : "Camara3",
"created_at" : ISODate("2017-01-26T18:53:34.447Z")
}
}

Resources