JavaScript Deeply nested array filtering methods - javascript

I am experimenting with deeply nested array filtering with JavaScript. I have created a solution which works but would anyone be able to demonstrate any alternative methods (faster or more efficient) how to accomplish the same task provided with the code below. function carReturn()
{
return myCars.filter(myCars => myCars.colour.includes("Red"));
} The scenario and the purpose of the code is to filter out the cars, which have color "Red" attached to them. Below I have attached the full demonstration of the code. Thanks for any help or recommendations.
<p>Car List.</p>
<p id="show"></p>
<p id="show1"></p>
<script>
const myCars = [
{ name: "BMW",colour: ["White","Red","Black"] },
{ name: "AUDI",colour: ["Yellow","Silver"] },
{ name: "VW",colour: ["Purple","Gold"] },
{ name: "NISSAN",colour: ["White","Black"] },
{ name: "SUZUKI",colour: ["Red"] },
{ name: "Lada",colour: ["Gray","Red"] },
];
function carReturn()
{
return myCars.filter(myCars => myCars.colour.includes("Red"));
}
var jol = carReturn();
document.getElementById("show").innerHTML += jol;
console.log(carReturn('Red'));
</script>
PS the innerHTML does not work but the functionality works within console. The posts used for reference has been: JavaScript filtering Filtering an array with a deeply nested array in JS

Related

USe data from another object VueJs

i have quick question here.
I have my object with value:
data() {
return {
nation: {
CZ: require("../../../../../svg/czech-flag.svg"),
}
};
},
Then have API object (API is working fine, fyi)
doctor: {
region: "CZ"
}
I wanna do something like this (is not working of course):
<div v-html="nation.doctor.region></div>
I had method for this, it worked, but I think it can be easier to do that. Thanks a lot for any help
You can use something like nations[`${doctor.region}`]
Working code:
const data = {
nations: {
CZ: 'Czech'
}
}
const doctor = {
region: 'CZ'
}
console.log(data.nations[`${doctor.region}`])

Javascript: Construct an object from array of objects based on matching property id's:

still quite new to higher order functions and trying to use them correctly here if possible.
I have a array of objects being returned from an api constructed like so:
[ {"gymId":3467, "halls": [{ "hallId": "25828", "instructorId": 1064,
"slotIds": [2088,2089], "sessionId":8188},
{"hallId": "25848", "instructorId": 1067, "slotIds": [2088,2089], "sessionId": 8188 }]}]
Expected result I want to achieve is to create a list of objects such as this from the array above ...
{2088: [{ "hallId":"25828", "instructorId":1064, "sessionId":8188 },
{ "hallId":"25848", "instructorId":1067, "sessionId":8188 }],
2089: [{ "hallId":"25828", "instructorId":1064, "sessionId":8188 },
{ "hallId":"25848", "instructorId":1067, "sessionId":8188 }]
}
I was thinking something along the lines of this
halls.reduce((acc, hall) => {
hall.slotIdIds.forEach(slotId => {
acc[slotId] = {
//expected object properties as above here.
};
});
return acc;
}, {}),
Problem is when I reduce in this way only one hallId is being returned and not the two matching hall ids where the slots exist.
Bit perplexed as to how to solve this one and would really appreciate any tips.

Native JavaScript Way to Walk up Document Tree When Comparing Objects

I have done some work to do a deep comparison (via Underscore and diff) between two objects (actually a pre-save and post-save version of the same document) in order to isolate the section that is different after a save. Take this document structure as an example:
{
_id: 4d39fe8b23dac43194a7f571,
name: {
first: "Jane",
last: "Smith"
}
services: [
{
service: "typeOne",
history: [
{ _id: 121,
completed: true,
title: "rookie"
},
{ _id: 122,
completed: false,
title: "novice"
}
]
},
{
service: "typeTwo",
history: [
{ _id: 135,
completed: true,
title: "rookie"
},
{ _id: 136,
completed: false,
title: "novice"
}
]
}
]
}
If a new element is added to the history array I'm able to successfully parse out that change.
However, in addition to pulling out this changed section, I also want to be able to effectively walk up from history in order to find the value for service, because I also need to know which of the two services array elements actually changed. Is there a way I can do this with native es6 JavaScript?
If not, is there a library I can use to determine this? Right now I'm able to get the value for "service" via indexing:
if (diff.path[1] === 0) {
targetService = "typeOne";
} else if (diff.path[1] === 1) {
targetService = "typeTwo";
} else if (diff.path[1] === 2) {
targetService = "typeThree";
}
But from my understanding this isn't full proof, because there's no guarantee the order of elements within "services" couldn't change at some point. I suppose this indexing method could work if I could enforce the ordering of the elements within the services array. I'm just not sure if there's a way to do that (open to suggestions if it is possible).
deep-diff gives you the path to this change, something like this:
{
kind: 'N',
path: ['services', 1, 'history'],
// ... other properties
}
You can use this path to track the changed object:
tree.services[changes.path[1]].service // 'typeTwo'

VueJs insert into nested list

I want to let the user create the structure of my website. For example, I have buildings and rooms. The user must be able to create a building and subsequently insert rooms into it. However, what I tried to do seems not to achieve it:
JSFiddle of what I have done so far.
js
new Vue({
el: '#vue-app',
data: {
buildings: []
},
computed: {
buildingCount() {
return this.buildings.length
},
getBuildingRoomsLength(section) {
return this.buildings.rooms.length
}
},
methods: {
addNewRoomToBuilding(buildingId, newRoom) {
if(newRoom !== undefined) { this.buildings[parseInt(buildingId)-1].rooms.push(newRoom.title)
console.log(this.buildings[parseInt(buildingId)-1])
}
},
addNewBuilding() {
this.buildings.push({
id: this.buildings.length+1,
rooms: []
})
},
deleteTodo(todo) {
this.todos.$remove(todo)
}
}
});
I am not sure how to make it work. A couple of the things I have noticed is that the room model now is same for all buildings and I have to change it according to the buildingId, however, I can't figure it out yet. Could you please assist me how to do this.
Make your model unique for each item in the buildings array by appending the building id to the end of the name.
So the model name becomes v-model="newRoom[building.id]"
And pass the same into your method addNewRoomToBuilding(building.id, newRoom[building.id])

Use mongoose to find by a nested documents properties

I currently have a collection of documents that each contain arrays pointing at other documents within that collection. I need to query this collection for documents where the ones nested in arrays contain a certain property. I hope this will explain my request more clearly:
if doc.list1[0].prop = 'foo' or doc.list2[0].prop = 'foo' then select doc
I have tried using .find() like this but to no avail.
{
'doc.list1': 'foo',
$or: [
{ 'doc.list2': 'foo' }
]
}
Am I on the right track? Because I don't think I am. This is the best I can gleam from the documentation.
Edit
Here is my actual query initialisation using the same layout as Thomas's suggestion.
var query = this.Word.find({
$or: [
{ 'before.0.cleanWord': topic },
{ 'after.0.cleanWord': topic },
{ 'cleanWord': topic }
]
});
{
$or: [
{ 'doc.list1.0.prop': 'foo' }
{ 'doc.list2.0.prop': 'foo' }
]
}
http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24or

Categories