Find child object with certain key value using lodash - lodash

I want to use lodash to go through an object of objects to find an object with a certain id value. the object has the following structure:
const a = {
"11": {
"id": 11,
},
"12": {
"id": 12,
},
}
lodash
findKey(a, ["id", 12])

You can use
ES5
var object = _.find(a,{id:12})
ES6
const object = _.find(a,{12})
More info at Lodash Docs

Related

v-select with groups from data via api

I get from my API this data:
[
{
"id":69,
"name":"Baupraxis",
"upper_id":7
},
{
"id":42,
"name":"bautipps.de",
"upper_id":4
},
{
"id":16,
"name":"Bellevue",
"upper_id":7
},
{
"id":18,
"name":"besser Bauen",
"upper_id":7
},
{
"id":2,
"name":"Besuch auf Betriebsgel\u00e4nde",
"upper_id":0
},
{
"id":7,
"name":"billiger Bauen",
"upper_id":0
}
]
I use it to fill a v-select like this:
<v-select
label="Anfrageart"
dense
:items="itemsRequestTypes"
item-text="name"
item-value="id"
v-model="requestType"
>
</v-select>
So here's what I'd like to solve, the upper_id is greater than zero if it is a subgroup of an item with the matching id. Means in upper_id is the id of the main group.
How can I group this in a v-select now?
I try to add a header in the object, but this didn't help.
You need to transform your data from the API before passing it to the template. Also, v-select supports nested option group using items where header type represents the group header which is non-selectable item.
const data = [
{
"id": 69,
"name": "Baupraxis",
"upper_id": 7
},
{
"id": 42,
"name": "bautipps.de",
"upper_id": 4
},
{
"id": 16,
"name": "Bellevue",
"upper_id": 7
},
{
"id": 18,
"name": "besser Bauen",
"upper_id": 7
},
{
"id": 2,
"name": "Besuch auf Betriebsgel\u00e4nde",
"upper_id": 0
},
{
"id": 7,
"name": "billiger Bauen",
"upper_id": 0
}
];
// Create an intermediate object to hold categories.
const groups = {};
// Create array for each group to main subgroup list.
data.forEach((x) => {
// create empty object if it doesn't exists.
groups[x.upper_id] = groups[x.upper_id] || { name: x.name, list: [] };
groups[x.upper_id].list.push(x);
});
// The flattened list of items that holds items as well as unique headers
const flattened = [];
// Iterate over all the unique categories and
// then flatten into a list that v-select needs.
Object.keys(groups).forEach((categoryId) => {
const catgory = groups[categoryId];
const categoryName = category.name;
// Create a group
flattened.push({ header: categoryName });
// Add all the items followed by category header
flattened.push(...category.list);
});

Ramda - how to add new property to objects in array

I am trying to add a new property to each object in the array. My test array:
const array = [
{
"name": 'Test'
},
{
"name": 'Test2'
}
]
I tried to use R.assoc('selected', false, array); but it didn't work as expected.
As a result, I would like to get:
const array = [
{
"name": 'Test',
"selected": false
},
{
"name": 'Test2',
"selected: false
}
]
Any help will be appreciated
R.assoc works by making a shallow clone of an object, and setting/updating a property. In this case, you need to handle an array of objects. Use R.map to iterate the array, and create a new array with transformed cloned objects by applying R.assoc:
const fn = R.map(R.assoc('selected', false));
const array = [{"name":"Test"},{"name":"Test2"}];
const result = fn(array);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js" integrity="sha512-rZHvUXcc1zWKsxm7rJ8lVQuIr1oOmm7cShlvpV0gWf0RvbcJN6x96al/Rp2L2BI4a4ZkT2/YfVe/8YvB2UHzQw==" crossorigin="anonymous"></script>

How to create array from computed property array field in vue?

I have a computed property that pulls some data out of my vuex store like so:
computed: {...mapGetters(["allCategories"])},
Each category in this.allCategories looks like so:
{ "id": "123", "name": "Foo" }
I want to pull out every name field from this.allCategories before the component is mounted in put each name into an reactive data property called categoryNames.
How can I achieve this?
What I have tried so far is below:
beforeMount() {
for (let i = 0; i < this.allCategories.content.length; i++) {
var name = this.allCategories.content[i].name
this.categoryNames.push(name);
}
},
Which gives the following error:
Error in beforeMount hook: "TypeError: Cannot read property 'length' of undefined"
this.allCategories looks like so:
{
"content": [
{
"id": "efb038df-4bc9-4e31-a37a-e805c9d7294e",
"parentCategoryId": "8ffc214f-fff1-4433-aac9-34d13b4e06c5",
"name": "Foo"
},
{
"id": "5905d437-db2e-4f91-8172-c515577b86e9",
"parentCategoryId": "5905d437-db2e-4f91-8172-c515577b86e9",
"name": "Bar"
},
{
"id": "8ffc214f-fff1-4433-aac9-34d13b4e06c5",
"parentCategoryId": "8ffc214f-fff1-4433-aac9-34d13b4e06c5",
"name": "Baz"
}
],
"number": 0,
"size": 100,
"total": 3
}
You could use the created hook to call a vuex action that calls a vuex mutation that grabs a state, do your parsing and store the parsed data in a new array in state, then use a getter to grab the parsed array from state.
created() {
this.$store.dispatch('someAction');
},
computed: {
...mapGetters({
parsedArray: 'getParsedArray',
})
}
export const actions = {
someAction({ commit }) {
commit('SOME_MUTATION');
},
}
export const mutations = {
SOME_MUTATION(state) {
let data = state.originalData;
let parsedArray = [];
// Do parsing work here
state.parsedArray = parsedArray
},
}
export const getters = {
getParsedArray: state => {
return state.parsedArray;
},
}

How to make ember work with Django REST gis

I am currently trying to setup ember to interact with Django's REST Framework using the ember-django-adapter.
This works flawless. But since I started using djangorestframework-gis, ember is not able to process the responses anymore.
I have not found anyone building geoJSON with ember except for: https://gist.github.com/cspanring/5114078 But that does not seem to be the right approach because I do not want to change the data model?
This is the api-response:
{
"type": "FeatureCollection",
"features": [
{
"id": 1,
"type": "Feature",
"geometry": {
"coordinates": [
9.84375,
53.665466308594
],
"type": "Point"
},
"properties": {
"date_created": "2014-10-05T20:08:43.565Z",
"body": "Hi",
"author": 1,
"expired": false,
"anonymous": false,
"input_device": 1,
"image": "",
"lat": 0.0,
"lng": 0.0
}
}
]
}
While ember expects something like:
[{"id":1,
"date_created":"2014-10-05T20:08:43.565Z",
"body":"Hi",
"author":1,
"expired":false,
"anonymous":false,
"input_device":1,
"image":"",
"lat":0,
"lng":0
}
]
My take on this was to write my own Serializer:
import Ember from "ember";
import DS from "ember-data";
export default DS.DjangoRESTSerializer.extend({
extractArray: function(store, type, payload) {
console.log(payload);
//console.log(JSON.stringify(payload));
var features = payload["features"];
var nPayload = [];
for (var i = features.length - 1; i >= 0; i--) {
var message = features[i];
var nmessage = {"id": message.id};
for(var entry in message.properties){
var props = message.properties;
if (message.properties.hasOwnProperty(entry)) {
var obj = {}
nmessage[entry]=props[entry];
}
}
nPayload.push(nmessage);
};
console.log(nPayload); //prints in the format above
this._super(store, type, nPayload);
},
})
But I receive the following error:
The response from a findAll must be an Array, not undefined
What am I missing here? Or is this the wrong approach? Has anyone ever tried to get this to work?
An alternative would be to handle this on the serverside and simply output a regular restframework response and set lat and long in the backend.
This is not a valid answer for the question above. I wanted to share my solution anyways,
just in case anyone ever gets into the same situation:
I now do not return a valid geoJSON, but custom lat, lng values. The following is backend code for django-rest-framework:
Model:
#models/message.py
class Message(models.Model):
def lat(self):
return self.location.coords[1]
def lng(self):
return self.location.coords[0]
And in the serializer:
#message/serializer.py
class MessageSerializer(serializers.ModelSerializer):
lat = serializers.Field(source="lat")
lng = serializers.Field(source="lng")
Ember can easily handle the format.

Adding an array element to all documents in a collection

My Foo documents have a CustomData collection used to add user-configurable properties.
Sometimes, when I create those properties, I'm need to add them with a default value for indexing purposes.
This is what I'm trying to use for that purpose:
DatabaseCommands.UpdateByIndex(
"dynamic/Foos",
new IndexQuery(),
new[]
{
new PatchRequest
{
Name = "CustomData",
Type = PatchCommandType.Add,
Value = RavenJObject.FromObject(new
{
Value = false,
Bar = new { Baz = "Qux"}
})
}
});
This generates the following HTTP request:
PATCH /databases/MyDb/bulk_docs/dynamic/Foos?&pageSize=128&allowStale=False
[
{
"Type": "Add",
"Value": {
"Value": false,
"Bar": {
"Baz": "Qux"
}
},
"Name": "CustomData"
}
]
And this returns 200 OK, but no documents are modified.
It looks like the problem is the usage of dynamic indexes.
Switching to a persistent index solved the problem.