Create a JSON object with variables as fields - javascript

I want to create a JSON object with variables as associative variable names similar to the following:
var field = 'first';
var query = { details.field, details.field };
I would prefer if the details were a fixed value.
This is my dataset currently
{
field1: ,
group: {
first:
}
}
My question is, how would I go about creating JSON objects with variables as fields?

You can add a property to an object like so:
var query = { details: {} };
var field = 'first';
query.details[field] = "TEST";
Which will give you the object:
{ details: { first: "TEST" }}
which you can then access with query.details.first or query.details[field];
Is that what you're looking for?

A simple way to accomplish this in Javascript is using the . operator.
query.details.field = "first";
This will product an object as follows:
"query" { "details" { "field": "first"} }
Is this what your looking for?
If you want multiple details you will want to use an array.
var query = [];
query.push({"details" { "field" : "first"} });
query.push({"details" { "field" : "second"} });
This will product an object like this
"query" [
"details" { "field" : "first"},
"details" { "field" : "second"}
]

Related

How to rename my property value but keep the other infos?

I have an object like this:
The thing I want to do is to rename the services.XXX value but keep his child properties.
For example I want to rename object.services.cadvisor with object.services.new-name
How can I do that ?
You can do the following
object.services.newName = object.services.cadvisor;
delete object.services.cadvisor
Copy the object to the new property and delete the old one
let myObj = {
services: {
cadvisor : {
name: 'Cadivsor',
length: 50,
nestedObject : {
name: 'Nested'
}
},
other : {}
}
};
myObj.services['newName'] = myObj.services.cadvisor;
delete myObj.services.cadvisor;
console.log(myObj);

Get unique id of specific element in Firebase

I have my Firebase database structured like this:
{
"userProfile" : {
"X0u2SEFfYEeVmdw4TXl58ou2eYy1" : {
"email" : "jane#yahoo.com",
"name" : "Jane"
},
"cliv7hQ4FsWKTtYksPDXcdDafdi2" : {
"email" : "doe#gmail.com",
"name" : "John Doe",
}
}
}
I'm trying to get the unique id of the element that matches query criteria, for example the key of the element with email equal to doe#gmail.com.
I'm doing this by using:
firebase.database().ref('/userProfile').orderByChild('email').equalTo(email).once( 'value', data => {
let user = data.val();
});
This returns me the entire object with that email, but I only want its unique id ("cliv7hQ4FsWKTtYksPDXcdDafdi2" in this case). What's the best way to achieve this?
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
So:
var query = firebase.database().ref('/userProfile').orderByChild('email').equalTo(email);
query.once( 'value', data => {
data.forEach(userSnapshot => {
let user = userSnapshot.val();
let key = userSnapshot.key;
});
});

How to search by object with nested object in AngularJS

I want to filter my orders collection by search object. want to show only matching order in view.
I have orders array collection like:
$scope.orders = [{
"_id" : "56461e2b7caaf49345076709",
"customer" : {"_id": "76461e2b7caaf49345076a19b", "name": "cr1"},
"seller" : {"_id": "96461e2b7caaf49345076a18b", "name": "sl1"},
"address" : "Squire Park",
"qt" : 5
},
{
"_id" : "56461e2b7caaf49345076708",
"customer" : {"_id": "76461e2b7caaf49345076a19b1", "name": "cr2"},
"seller" : {"_id": "96461e2b7caaf49345076a18c1", "name": "sl2"},
"address" : "Squire Park1",
"qt" : 6
},
..................
];
and my search object like:
$scope.search = {
"qt": 5,
"customer" : {"_id": "76461e2b7caaf49345076a19b1"},
"seller" : {"_id": "96461e2b7caaf49345076a18c1"}
};
view:
<tr data-ng-repeat="order in orders | myFilter:search">
<td>{{order._id}}</td>
<td>{{order.customer.name}}</td>
</tr>
What should be my myFilter function?
Thanks advance.
A rather simple solution would be attaching a filter function to the scope
$scope.orderFilter = function(order) {
// implementation depends on how you want the search to behave
// for example, if the order should match every property of the searchObj
var pass = true;
for (var property in $scope.search) {
if ($scope.search.hasOwnProperty(property)) {
if($scope.search[property] != order[property]) {
pass = false;
}
}
}
return pass;
// .. though i wouldnt recommend this implementation
// you´d be better off by implementing a more specific matching
}
And in the view
<tr data-ng-repeat="order in orders | filter:orderFilter">
<td>{{order._id}}</td>
<td>{{order.customer.name}}</td>
</tr>
If you want the filter-expression you are using to work, you have to register a custom filter on your module. This would be done like so:
angular.module('app').filter('myFilter', function() {
return function(orders, searchObj) {
var filteredOrders = [];
orders.forEach(function(order) {
// evaluate if you want to have the order show up based on the searchOjb
// .. if so, add it to the array like so:
filteredOrders.push(order);
});
return filteredOrders;
}
});
NOTE
If you change a property of you search object, your filter function wont be called again, because angular filters arent listening for changes of nested properties. The filter will only be called if you change the whole search object.

Javascript - delete object from reference

I have one tree-like structure containing block with certain id. Then I have another object, that contains 'id' : objectPart pairs.
Tree:
var tree = [
{
'property' : 'value',
'id' : 'someID',
//more properties...,
'content' : [
{
'prop' : 'something',
...
}
]
},
{
'prop' : 'val',
...
'content' : []
}
]
ID index:
{
'someID' : tree[0]
}
I need some way how when I do delete ID_index.someID, that object gets also deleted from main structure.
Structure after this code should look like this:
[
{
'prop' : 'val',
...
'content' : []
}
]
Instead of using delete you can write your own remove function. It should look like this:
function myRemove(stringId) {
delete ID_index[stringId]; //remove property from ID_index
objIndex = ... //find object index in tree array
tree.splice(objIndex, 1); //remove object from tree array
}

Using objects to store a list of names

I was wondering how to use an object to store a list of different names and access them by simply using the key.
Do I have to use embedded object like this.
var f =
{
0 : { name : "John" },
1 : { name : "Phillip" }
};
console.log(f[1].name);
Do not over-complicate things. Why don't you just try a simple array?
var f = [
{ name : "John" },
{ name : "Phillip" }
];
console.log(f[1].name);
Why not just an array, which is indexed identically? Do you actually need a name: attribute for some reason?
var names = [ 'John', 'Phillip' ];
Instead of names[0].name, which is pretty redundant, you'd just use names[0]...
He wants to access them by key:
var people = {
John:{ age:33},
Bob :{ age:42}
};
Now you can truly access them by key:
console.log(people["John"].age);
or this way (although odd):
console.log(people.John.age);
No looping is necessary, you are using the power of javascripts associative syntax to index directly into your data structure. No need to refer to some arbitrary integer index either.
This definitely works but typically you'd use a more appropriate property to index than just a name like perhaps an employee id.
You can use like this
Var names = [
{ 'name' : 'ashwin', age: 18 },
{'name' : 'jhon', 'age' : 20 }
];
console.log ( names[0].name );

Categories

Resources