Is it possible to get list of attributes of a particular JSON map with a JSONPath expression? For example:
{"foo": 1, "bar": 2} => ["foo","bar"]
You can use the following code:
Object.getOwnPropertyNames({"foo": 1, "bar": 2})
Here's a link for further information.
Loop through each json object get all the keys and push then into an array. You can try this:
var data=[{"foo": 1, "bar": 2},{"foo1": 1, "bar1": 2}];
var array=[];
$.each(data, function(key, value){
var item;
item=Object.keys(value);
array.push(item);
});
console.log(array);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
In Java we could do the following
public class TempClass {
List<Integer> myList = null;
void doSomething() {
myList = new ArrayList<>();
myList.add(10);
myList.remove(10);
}
}
But if we rewrite it to Kotlin directly as below
class TempClass {
var myList: List<Int>? = null
fun doSomething() {
myList = ArrayList<Int>()
myList!!.add(10)
myList!!.remove(10)
}
}
I got the error of not finding add and remove function from my List
I work around casting it to ArrayList, but that is odd needing to cast it, while in Java casting is not required. And that defeats the purpose of having the abstract class List
class TempClass {
var myList: List<Int>? = null
fun doSomething() {
myList = ArrayList<Int>()
(myList!! as ArrayList).add(10)
(myList!! as ArrayList).remove(10)
}
}
Is there a way for me to use List but not needing to cast it, like what could be done in Java?
Unlike many languages, Kotlin distinguishes between mutable and immutable collections (lists, sets, maps, etc). Precise control over exactly when collections can be edited is useful for eliminating bugs, and for designing good APIs.
https://kotlinlang.org/docs/reference/collections.html
You'll need to use a MutableList list.
class TempClass {
var myList: MutableList<Int> = mutableListOf<Int>()
fun doSomething() {
// myList = ArrayList<Int>() // initializer is redundant
myList.add(10)
myList.remove(10)
}
}
MutableList<Int> = arrayListOf() should also work.
Defining a List collection in Kotlin in different ways:
Immutable variable with immutable (read only) list:
val users: List<User> = listOf( User("Tom", 32), User("John", 64) )
Immutable variable with mutable list:
val users: MutableList<User> = mutableListOf( User("Tom", 32), User("John", 64) )
or without initial value - empty list and without explicit variable type:
val users = mutableListOf<User>()
//or
val users = ArrayList<User>()
you can add items to list:
users.add(anohterUser) or
users += anotherUser (under the hood it's users.add(anohterUser))
Mutable variable with immutable list:
var users: List<User> = listOf( User("Tom", 32), User("John", 64) )
or without initial value - empty list and without explicit variable type:
var users = emptyList<User>()
NOTE: you can add* items to list:
users += anotherUser - *it creates new ArrayList and assigns it to users
Mutable variable with mutable list:
var users: MutableList<User> = mutableListOf( User("Tom", 32), User("John", 64) )
or without initial value - empty list and without explicit variable type:
var users = emptyList<User>().toMutableList()
//or
var users = ArrayList<User>()
NOTE: you can add items to list:
users.add(anohterUser)
but not using users += anotherUser
Error: Kotlin: Assignment operators ambiguity:
public operator fun Collection.plus(element: String): List defined in kotlin.collections
#InlineOnly public inline operator fun MutableCollection.plusAssign(element: String): Unit defined in kotlin.collections
see also:
https://kotlinlang.org/docs/reference/collections.html
Agree with all above answers of using MutableList but you can also add/remove from List and get a new list as below.
val newListWithElement = existingList + listOf(element)
val newListMinusElement = existingList - listOf(element)
Or
val newListWithElement = existingList.plus(element)
val newListMinusElement = existingList.minus(element)
Apparently, the default List of Kotlin is immutable.
To have a List that could change, one should use MutableList as below
class TempClass {
var myList: MutableList<Int>? = null
fun doSomething() {
myList = ArrayList<Int>()
myList!!.add(10)
myList!!.remove(10)
}
}
Updated
Nonetheless, it is not recommended to use MutableList unless for a list that you really want to change. Refers to https://hackernoon.com/read-only-collection-in-kotlin-leads-to-better-coding-40cdfa4c6359 for how Read-only collection provides better coding.
In Kotlin you must use MutableList or ArrayList.
Let's see how the methods of MutableList work:
var listNumbers: MutableList<Int> = mutableListOf(10, 15, 20)
// Result: 10, 15, 20
listNumbers.add(1000)
// Result: 10, 15, 20, 1000
listNumbers.add(1, 250)
// Result: 10, 250, 15, 20, 1000
listNumbers.removeAt(0)
// Result: 250, 15, 20, 1000
listNumbers.remove(20)
// Result: 250, 15, 1000
for (i in listNumbers) {
println(i)
}
Let's see how the methods of ArrayList work:
var arrayNumbers: ArrayList<Int> = arrayListOf(1, 2, 3, 4, 5)
// Result: 1, 2, 3, 4, 5
arrayNumbers.add(20)
// Result: 1, 2, 3, 4, 5, 20
arrayNumbers.remove(1)
// Result: 2, 3, 4, 5, 20
arrayNumbers.clear()
// Result: Empty
for (j in arrayNumbers) {
println(j)
}
UPDATE: As of Kotlin 1.3.70, the exact buildList function below is available in the standard library as an experimental function, along with its analogues buildSet and buildMap. See https://blog.jetbrains.com/kotlin/2020/03/kotlin-1-3-70-released/.
Confining Mutability to Builders
The top answers here correctly speak to the difference in Kotlin between read-only List (NOTE: it's read-only, not "immutable"), and MutableList.
In general, one should strive to use read-only lists, however, mutability is still often useful at construction time, especially when dealing with third-party libraries with non-functional interfaces. For cases in which alternate construction techniques are not available, such as using listOf directly, or applying a functional construct like fold or reduce, a simple "builder function" construct like the following nicely produces a read-only list from a temporary mutable one:
val readonlyList = mutableListOf<...>().apply {
// manipulate your list here using whatever logic you need
// the `apply` function sets `this` to the `MutableList`
add(foo1)
addAll(foos)
// etc.
}.toList()
and this can be nicely encapsulated into a re-usable inline utility function:
inline fun <T> buildList(block: MutableList<T>.() -> Unit) =
mutableListOf<T>().apply(block).toList()
which can be called like this:
val readonlyList = buildList<String> {
add("foo")
add("bar")
}
Now, all of the mutability is isolated to one block scope used for construction of the read-only list, and the rest of your code uses the read-only list that is output from the builder.
You can do with create new one like this.
var list1 = ArrayList<Int>()
var list2 = list1.toMutableList()
list2.add(item)
Now you can use list2, Thank you.
https://kotlinlang.org/docs/reference/collections.html
According to above link List<E> is immutable in Kotlin.
However this would work:
var list2 = ArrayList<String>()
list2.removeAt(1)
A list is immutable by Default, you can use ArrayList instead. like this :
val orders = arrayListOf<String>()
then you can add/delete items from this like below:
orders.add("Item 1")
orders.add("Item 2")
by default ArrayList is mutable so you can perform the operations on it.
In concept of immutable data, maybe this is a better way:
class TempClass {
val list: List<Int> by lazy {
listOf<Int>()
}
fun doSomething() {
list += 10
list -= 10
}
}
If I have helpers like:
Handlebars.registerHelper("testHelper", function (v) {
console.log(v);
}
Handlebars.registerHelper("testHelper2", function (v) {
return v;
}
and have two subhelpers like:
{{testHelper first=(testHelper2 '1') second=(testHelper2 '2')}}
both first and second are returning '2'. The console output is:
data: {},
hash: {
first: '2',
second: '2'
}
How would I make it return the correct values? If I do the following it returns first as 1:
{{testHelper first=(testHelper2 '1')}}
Does anyone have a workaround for this? Please note that I made the helpers simple and wouldn't use a helper to return the same value normally.
Here is a fiddle example.
The only way that I see is to not use a hash as parameter for first helper. Instead of it use arguments directly.
Helper:
Handlebars.registerHelper("testHelper", function () {
var args = Array.prototype.slice.call(arguments, 0);
return 'first: '+args[0]+' second: '+args[1];
});
Template:
{{testHelper (testHelper2 '1') (testHelper2 '2')}}
Fiddle.
Handlebars.js has some weird behavior. It renders a boolean with a value of true as the string "true", but a value of false as "".
var booleanTestTrue = true;
var booleanTestFalse = false;
Template:
True: {{booleanTestTrue}}
False: {{booleanTestFalse}}
Renders to:
True: true
False: (empty string)
Is there any way to fix this problem? Or do I have to write a helper?
You can use a simple block helper and implement #if like the following:
{{#if isTrue}}
true
{{else}}
false
{{/if}}
If you want to print a string, you should pass a string.
false.toString();
Otherwise, yeah you would need a helper (unless you use the #if|#unless helpers to output a string).
On a side note, if you wanted to print these values for debugging purpose, use the {{log booleanTestFalse}}.
I was surprised by this, and ended up writing a simple helper for it:
Handlebars.registerHelper( 'toString', function returnToString( x ){
return ( x === void 0 ) ? 'undefined' : x.toString();
} );
You would then invoke it as follows:
True: {{toString booleanTestTrue}}
False: {{toString booleanTestFalse}}
In most scenarios you could get away with simply return x.toString(). The extra checking avoids attempting to call toString on undefined values.
I used this, similar to Barney's answer but supports null too.
Handlebars.registerHelper('toString', function (v) {
return '' + v;
});
You would then invoke it as follows:
True: {{toString booleanTestTrue}}
False: {{toString booleanTestFalse}}
However if v is an object with a pretty toString method you need to do more coding.
I have document like this:
{
"_id": ObjectId("4d17c7963ffcf60c1100002f"),
"title": "Text",
"params": {
"brand": "BMW",
"model": "i3"
}
}
{
"_id": ObjectId("4d17c7963ffcf60c1100002f"),
"title": "Text",
"params": {
"brand": "BMW",
"model": "i5"
}
}
What i need is the count of every params values. like:
brand
---------
BMW (2)
model
---------
i3 (1)
i5 (1)
I think i have to write map/reduce functions. How can i do this? Thanks.
I think i have to write map/reduce functions.
Yes you need a map-reduce for this. For some simple map-reduce examples, please look here.
For your particular case, you first need to change your expectation of the output. The output of the map / reduce is a collection. The collection will look (in your case) something like this:
{ key : { 'brand' : 'bmw' }, value : 2 }
{ key : { 'model' : 'i5' }, value : 1 }
To generate this set you will need a "map" function and a "reduce" function. The "map" function will emit a key and a value. The key is each element of params, the value is the count of 1. The "reduce" function accepts a key and an array of values and returns just a single value. Your question is basically the same as this example on the MongoDB site:
map = function() {
if (!this.params) {
return;
}
for (index in this.params) {
emit(this.params[index], 1);
}
}
reduce = function(previous, current) {
var count = 0;
for (index in current) {
count += current[index];
}
return count;
}
In your map function enumerate the properties of the params property of the this object. For each property you find call emit with a key that contains both the name of the property and the value of the property. Pass 1 as the value. e.g. emit({'brand','BMW'}, 1) but obviously using variables not constants!
In your reduce function you are passed a key and an array of values. Sum these values and return the sum. Even though the initial array will be all 1's don't be tempted to use the length of the array because the reduce function can be called iteratively.
You can group the results afterwards from the result collection, applying an index if necessary for performance.