I need to store many values in single key of json. e.g.
{
"number" : "1","2","3",
"alphabet" : "a", "b", "c"
}
Something like this. Any pointers?
Use arrays:
{
"number": ["1", "2", "3"],
"alphabet": ["a", "b", "c"]
}
You can the access the different values from their position in the array. Counting starts at left of array at 0. myJsonObject["number"][0] == 1 or myJsonObject["alphabet"][2] == 'c'
{
"number" : ["1","2","3"],
"alphabet" : ["a", "b", "c"]
}
{
"success": true,
"data": {
"BLR": {
"origin": "JAI",
"destination": "BLR",
"price": 127,
"transfers": 0,
"airline": "LB",
"flight_number": 655,
"departure_at": "2017-06-03T18:20:00Z",
"return_at": "2017-06-07T08:30:00Z",
"expires_at": "2017-03-05T08:40:31Z"
}
}
};
Related
I am trying to perform an aggregate query in MongoDB. My target is to check if any values within an array exists in another array and conditionally introduce a third variable accordingly.
For example, I have an array A => ["a", "b"] and another array B => ["a", "c", "d"]
So in this case as "a" exists in both A & B, they should match.
aggregate.push({
"$addFields": {
"canClaim": {
$cond: [{
$in: [["a", "b"], ["a", "c", "d"]]
}, 1, 0]
}
}
})
Does this help you?
db.collection.aggregate({
"$addFields": {
"c": {
"$setIntersection": [
"$a",
"$b"
]
}
}
},
{
"$match": {
"c.1": {
"$exists": true
}
}
})
Mongo Playground
I want to replace all A characters present in an array with 15 using Swift 3.
Example array:
["4", "5", "6", "A", "A", "Q", "A"]
Desired result:
["4", "5", "6", "15", "15", "Q", "15"]
map to the rescue:
var a = ["4", "5", "6", "A", "A", "Q", "A"]
a = a.map({ $0 == "A" ? "15" : $0 })
print(a)// ["4", "5", "6", "15", "15", "Q", "15"]
EDIT: After error screenshot:
You have an array of characters and hence the above code is not working. Also, remember "15" is two characters and not one character. Hence, I have replaced character 'A' with string "15" and mapped it to an array of strings, instead
let player1 = "456AAQA"
var player1Cards = Array(player1.characters) // ["4", "5", "6", "A", "A", "Q", "A"]
var player1CardsStrings = player1Cards.map{$0 == "A" ? "15" : String($0)}
player1CardsStrings // ["4", "5", "6", "15", "15", "Q", "15"]
Tested on Playground.
Because your question is lacking information that you didn't gave at first, here is what you can do.
"for loop": You iterate and replace the value if needed.
That's a logic you could apply on almost all languages.
var array1 = ["4", "5", "6", "A", "A", "Q", "A"]
for index in 0 ... array1.count-1
{
if array1[index] == "A"
{
array1[index] = "15"
}
}
print("array1: \(array1)")
"for each loop": You iterate and replace the value if needed.
That's a logic you could apply on almost all languages (maybe less languages that the previous one)
var array2 = ["4", "5", "6", "A", "A", "Q", "A"]
for (index, object) in array2.enumerated()
{
if object == "A"
{
array2[index] = "15"
}
}
print("array2: \(array2)")
"map": the "map" iterate for you (here is the important part behind the magic), you check the value and replace the value if needed. The $0 represent the "current item".
Here is a specificity.
var array3 = ["4", "5", "6", "A", "A", "Q", "A"]
array3 = array3.map({
if $0 == "A"
{
return "15"
}
return $0
})
print("array3: \(array3)")
"map": the "map" iterate for you, you check the value and replace the value if needed with a ternary if test.
var array4 = ["4", "5", "6", "A", "A", "Q", "A"]
array4 = array4.map({$0 == "A" ? "15" : $0})
print("array4: \(array4)")
I'm gave 4 ways (I've could also have explicit more the map() with explicit closure, from the simplest to the more complicated. We can't know if you don't show your attempts where you are are stucked. Is it for loop? The basic algorithms?
Swift advanced user may be more fond of the last one, but for beginners, it's quite complex and "magic". So when they want to change it a little for a different test, they never know what to do.
Side note: I'm not a Swift developer, more an Objective-C, so it may be lacking of checks. This answers is to show different approaches, how you go from a "verbose" to a less "verbose" code, but that you need to master anyway. Even if you have issue with map(), you can "bypass" it and do it manually.
let values = ["4", "5", "6", "A", "A", "Q", "A"]
let mappedvalues = values.map({ (value: String) -> String in
if value != "A" {
return value
}
return "15"
})
i have collection called 'test' in that there is a document like:
{
"_id" : 1
"letters" : [
[ "A", "B" ],
[ "C", "D" ],
[ "A", "E", "B", "F" ]
]
}
if i updated the document by using $addToSet like this:
db.getCollection('test').update({"_id" : 1}, {$addToSet:{"letters": ["A", "B"] }})
it will not inserted another value. still the document look like
{
"_id" : 1
"letters" : [
[ "A", "B" ],
[ "C", "D" ],
[ "A", "E", "B", "F" ]
]
}
if im updating like this:
db.getCollection('test').update({"_id" : 1}, {$addToSet:{"letters": ["B", "A"] }})
Now it will update the document like:
{
"_id" : 1
"letters" : [
[ "A", "B" ],
[ "C", "D" ],
[ "A", "E", "B", "F" ],
[ "B", "A" ]
]
}
my requirment is if im give like this also (["B", "A"]), it will not update that document. Because the same letters are already present in the array.
could anyone can please give the solution.
#Shubham has the right answer. You should always sort your letters before saving into the document. So your original document should have been (I changed the third array):
{
"_id" : 1,
"letters" : [
[ "A", "B" ],
[ "C", "D" ],
[ "A", "B", "C", "F" ]
]
}
Then in your application do the sort. I'm including a Mongo Shell example here.
var input = ["B", "A"];
input.sort();
db.getCollection('test').update({"_id" : 1}, {$addToSet:{"letters": input}});
Try this answer , it works.
Use $push to insert any item in the array in your case.
db.getCollection('stack').update(
{ _id: 1 },
{ $push: { "letters": ["B", "A"] } }
)
For reference about $push you can view this link -
https://docs.mongodb.com/manual/reference/operator/update/push/
I have some entries like:
{ "name":"a", "value":10 }
{ "name":"b", "value":20 }
{ "name":"c", "value":10 }
...
And I can select names from a query with db.collection.find({"value":10},{"name":1, _id: false}). It gives me the following:
{ "name" : "a" }
{ "name" : "c" }
...
However, I want it to return an array of values, not a set of { key : value } pairs. (like [ "a", "c", ... ]). Is there a way to achieve this with only MongoDB queries or should I select and put them in an array in my application?
Current Output:
{ "name" : "a" }
{ "name" : "c" }
...
Expected output:
["a", "c", ...]
If the above is not a possible output, it may be also
{ "result": ["a", "c", ...] }
db.collection.distinct( "name", { "value": 10 })
from #Sagar Reddy comment will return a set array:
["a", "c"]
This is probably what you need. Aniway, a similar more complex query can be achieved using aggregation, where you can use extra aggregation stages.
db.collection.aggregate([
{ $match: { value: 10 }},
{ $group: { _id: null, result: { $addToSet: '$name' }}},
{ $project: { _id: 0, result: 1 }}
])
In the group stage, addToSet can be replaced with push if you want the same value to appear multiple times.
Output using addToSet:
{ "result" : [ "c", "a" ] }
Ex output using push:
{ "result" : [ "a", "c", "c" ] }
I am trying to combine two two arrays to make a full deck of cards that looks like so:
[{card: "A", suit: "d"}, {card: "A", suit: "c"}, {card: "A", suit: "s"}, {card: "A", suit: "h"}, {card: "2", suit: "d"}.....]
.... this is what I have so far:
function newDeck(ranks, suits){
var ranks = [ "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
var suits = ["d", "c", "s", "h"]
var deck= []
for (i = 0; i < suits.length; i++) {
for (j = 0; j < ranks.length; j++) {
this.deck[ranks.length*i+j] = new Card(ranks[j], suits[i]);
}
} console.log(newDeck)
}
Using Array.forEach you can do the following:
var ranks = [ "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];
var suits = ["d", "c", "s", "h"];
var deck= [];
suits.forEach(function(suit){
ranks.forEach(function(rank){
deck.push(new Card(rank, suit));
})
});
EDIT: and in case you haven't written the Card method yet:
function Card(rank, suit){
this.card = rank;
this.suit = suit;
}
If you combine the two arrays you will have an array:
["A","2","3","4","5","6","7","8","9","10","J","Q","K","d","c","s","h"]
which does not represent a full deck of card, whereas using an embedded for loop to print out card as you are now will so I don't think you just want to append one array to the other. Can you provide more context on what you want to do with the array?
However, to answer your question: if you want to append two arrays you can use:
var appendedArray = ranks.concat(suits);
which will result in the aforementioned array above
pertaining to your updated question: you are called "new Card(ranks[j], suits[i]);" have you made a Card constructor so that this is valid? if so, the code should be correct if the constructor matches how you are using it. Posting the code for the constructor would be helpful along with an update of what issue you are facing