Lodash: filter when I have nested array property? - lodash

Consider below example. I am using Lodash
"home":[
{
"data":{
"interests":["sports", "travel", "boxing"],
"city":["x", "y", "z"],
"name":"test1"
},
"count":["1", "2"],
"country":"CA"
},
{
"data":{
"interests":["painting", "travel", "dancing"],
"city":["a", "y", "b"],
"name":"test2"
},
"count":["1","3"],
"country":"US"
}
]
If I'll try the function on key value pair example :
_.find(home, ['data.country', 'US']); // It is returning me the 2nd object
requirement :
I want all the objects where data.interests is 'dancing'.
Tried :
_.find(home, ['data.interests', 'dancing']) // It is returning []
I have also tried filter(), where() and map but unable to get the complete object.
Thanks in advance.

You can use vanilla JS or lodash funcntions - Filter the array, and for each item check if the data.interests array includes the requested word.
Vanilla:
const home = [{"data":{"interests":["sports","travel","boxing"],"city":["x","y","z"],"name":"test1"},"count":["1","2"],"country":"CA"},{"data":{"interests":["painting","travel","dancing"],"city":["a","y","b"],"name":"test2"},"count":["1","3"],"country":"US"}]
const result = home.filter(o => o.data.interests.includes('dancing'))
console.log(result)
Lodash:
const home = [{"data":{"interests":["sports","travel","boxing"],"city":["x","y","z"],"name":"test1"},"count":["1","2"],"country":"CA"},{"data":{"interests":["painting","travel","dancing"],"city":["a","y","b"],"name":"test2"},"count":["1","3"],"country":"US"}]
const result = _.filter(home, o => _.includes(o.data.interests, 'dancing'))
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

Related

React Native - Using promises when fetching and returning them to components

i want to display related data on react native, i have 2 response api
response 1
{
"total": 2,
"data" : [
{
"date" : "2020-12-01",
"time" : "08:00:00"
},
{
"date" : "2020-12-02",
"time" : "09:00:00"
}
]
}
response 2, date is parameter
date : 2020-12-01
{
"total": 2,
"data" : [
{
"date" : "2020-12-01",
"description" : "bla bla bla"
},
{
"date" : "2020-12-01",
"description" : "vla vla vla"
}
]
}
date : 2020-12-02
{
"total": 1,
"data" : [
{
"date" : "2020-12-02",
"description" : "cla cla cla"
}
]
}
how to use promises on fetch and how components return them,
so it can display content descriptions like this
Are you asking how to use promises with Fetch? Or how to take the results of those promises and use them to create a visual component?
It doesn't look like you've put any work into asking this question and it's quite wide ranging, from setting up components, creating fetch requests to an API and formatting them into visual components.
I'd consider starting here for your fetch request:
https://reactnative.dev/docs/network#making-requests
Then look at how they take the text and place it on a screen here:
https://reactnative.dev/docs/network#making-requests
EDIT:
Per the comments below.
You would most likely want to store the results of your request in some form of local state, and pass that state to your FlatList or similar, for instance:
const PromiseExample = () => {
const [listItems, setListItems] = useState([])
useEffect(() => {
async function fetchData() {
const data = await fetch('localhost:3000/data').json()
const otherData = await fetch('localhost:3000/otherData').json()
let joinedData = []
// at this point you would join your two data structures in whatever way you need to and push the joined data to the var.
setListItems(joinedData)
}
}, [])
return (
<FlatList data={listItems} />
)
}

Unable to copy an array to an array using vue.js

I have a multiple selectbox using vuetify select component. I'm getting array of selected items and I want to merge status as true of selected items like [ { "ward": 1, "status": true }, { "ward": 2, "status": true} ]
I'm trying to copy selected items of array to another array but couldn't succeed. In console, I got selectedFruits as below.
methods: {
save() {
console.log(this.selectedFruits);
debugger;
this.selectedIndex.push({ ward: this.selectedFruits, status: true });
console.log(this.list);
},
You can try this
save(){
this.list = []
this.selectedFruits.forEach(e => {
this.list.push({ ward: e, status: true });
});
console.log(this.list)
}
If you want to copy an array or object without passing it by reference, do it like this
const newArray = JSON.parse(JSON.stringify(oldArray));
You can use the Spread-Operator for this.
Here an example:
const existingArr = [{ hi: 'foobar' }];
const arr = [{ a: 'foo', b: 'bar'}, { a: 'hello', b: 'world'}]
const newArr = [...existingArr, ...arr]
console.log(newArr)

Filtering 2 or more categories in vue.js

I have a code where i filtered an array with a specific category.
response.data.items.filter(item => item.category_id === categ_id_1)
Now i want to add more categories in the filter (categ_id_2, categ_id_3). How do i do that?
Assuming the category_id is a primitive (ie string, number, etc), the easiest way I can think of is to maintain a Set of wanted categories and use Set.prototype.has() for filtering.
const categories = new Set(['categ_id_1', 'categ_id_2', ...])
response.data.items.filter(({ category_id }) => categories.has(category_id))
If you're wanting the list to be reactive in Vue, something like this...
data: () => ({
categoryFilters: ['categ_id_1', 'categ_id_2']
}),
computed: {
categoryFilterSet () {
return new Set(this.categoryFilters)
}
},
methods: {
async loadAndFilterData () {
const response = await axios({...}) // just guessing
const filtered = response.data.items.filter(({ category_id }) =>
this.categoryFilterSet.has(category_id))
}
}
The reason for using the computed property is that Vue does not work reactively with Set so you must back it up with an array.
Another way using Array.prototype.includes() which is used to pass/fail the test of filter for each element.
const items = [{
"a": 1,
"category_id": "categ_id_1"
}, {
"a": 2,
"category_id": "categ_id_2"
}, {
"a": 3,
"category_id": "categ_id_3"
}, {
"a": 4,
"category_id": "categ_id_4"
}, {
"a": 5,
"category_id": "categ_id_5"
}];
const search = ["categ_id_2", "categ_id_3"];
const result = items.filter(e => search.includes(e.category_id));
console.info("result::", result);
Try it as
response.data.items.filter(item => item.category_id === categ_id_1 ||item.category_id === categ_id_2 ||item.category_id === categ_id_3)

lodash filter deeply nested objects returning array of those objects

I'm trying to return an array of objects that are deeply nested in another array. Here is a sample object with arrays:
payment = {
"id": 1,
"tickets" = [{
"id": 1,
"ticketItems": [{item1}, {item2}, {item3}]
},
{"id": 2",
"ticketItems": [{item4}, {item5}, {item6}]
}]}
Using lodash I would like to return an array of just items 1-6 without the parent objects. I've tried:
var items = _.filter(payment.tickets, {'ticketItems'});
But that doesn't return an array of ticketItems. All the examples I've found use a condition like "id: 1", but I want all of the ticketItems, not just those matching a condition.
You can use Array.flatMap() (or lodash's _.flatMap()) and return the ticketItems from each tickets object:
const payment = {"id":1,"tickets":[{"id":1,"ticketItems":[{"item1":1},{"item2":2},{"item3":3}]},{"id":2,"ticketItems":[{"item4":4},{"item5":5},{"item6":6}]}]}
const result = payment.tickets.flatMap(o => o.ticketItems)
console.log(result)
And the same solution with lodash's _.flatMap():
const payment = {"id":1,"tickets":[{"id":1,"ticketItems":[{"item1":1},{"item2":2},{"item3":3}]},{"id":2,"ticketItems":[{"item4":4},{"item5":5},{"item6":6}]}]}
const result = _.flatMap(payment.tickets, 'ticketItems')
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

How To Access All Indexes In Nested Array (Vue-chartjs)

so I am trying to display data on my doughnut chart and I am having issues accessing my data from a nested array. When I use the following it just gives me the selected index of the nested array.
So I am wondering is there something else I need to do the computed data or if there is something I am doing wrong.
here is the computed property
countEngagementsByStatus () {
const selectedWorkflow = this.allWorkflows.filter(workflow => workflow.id === this.workflowKey)
const res = selectedWorkflow.map(({statuses, id}) => ({
workflow_id: id,
statuses: statuses.reduce((acc, cur) => {
const count = this.allEngagements.filter(({workflow_id, status}) => workflow_id === id && status === cur.status).length;
acc.push(count);
return acc;
}, [])
}))
return res
},
And on my doughnut chart I am accessing the data. *note removed styling data to clean up the question
datasetsfull() {
return {
labels: this.mapStatuses[0].statuses,
datasets: [
{
label: 'Data One',
data: [
//this is the line I have issues with
this.countEngagementsByStatus[0].statuses[0]
]
}
]
}
},
here is an image of what I am getting
Now If I do this
data: [
this.countEngagementsByStatus[0]
]
I get this as a result however it cannot access the array of numbers shown
So my question is, am I doing something wrong with computed property or am I accessing the data incorrectly or both? Lol
Here is a Js Fiddle To give an idea
So my issue was I was wrapping the data in an array
data: [
this.countEngagementsByStatus[0].statuses
]
I changed it to this
data: this.countEngagementsByStatus[0].statuses