How to get keys from anArray Object in reactjs - arrays

i have the following Array Object :
[
{
"key1": abc,
"key2":xyz
},
{
"key1": abc,
"key2":xyz
}
]
Now what i want is to print "key1" & "key2". I know we can iterate through values using map, but i also want to iterate through Array keys.

Assuming ArrayObj contains the key:value pairs, we can do the following:
let keys = Object.keys(ArrayObj);
for(index=0;index<keys.length;index++)
{
console.log(keys[index]);
}

Related

Ensure an array of documents exist in a collection

I have a collection with approximately 40k documents that look like this:
{
"_id":{"$oid":"5e988b703117c034b0630f8"},
"name":"London Heathrow Airport",
"country":"United Kingdom",
"iata":"LHR",
...
}
I want to be able to work through an array (actually a Javascript Map, which could have many hundreds of elements) like this:
["LHR", "LGW", "BFS", ...]
The items in this array relate to the iata property on the document.
I want to return an array where the elements that cannot be found in the collection are returned, and if all elements can be found then to return either a null value or empty array. So for example if "LHR" and "LGW" match the iata property of a document in the collection, but "BFS" doesn't, it should return ["BFS"]
I could interate through the array, making an individual query for each item in the array, but if the input array has many hundreds of elements, this seems very inefficient. Is there a better way!?
Thanks
You can query your collection for matching iata codes and do a diff between the result and your array of iata codes:
Given a collection airports with the following documents:
{
"_id": 1,
"name":"London Heathrow Airport",
"country":"United Kingdom",
"iata":"LHR",
},
{
"_id": 2,
"name":"Ljubljana Airport",
"country":"Slovenia",
"iata":"LJU",
},
Given the array of iata below:
var iatas = ["LHR", "LJU", "BFS"];
Find the matching documents and return result as an array of iata values:
var result = [];
db.airports.find({
"iata": {
$in: iatas
}
}).toArray().map(
function(u) {
result.push(u.iata)
}
);
The result will look like:
//result
[
"LHR",
"LJU"
]
Now you can do a diff between result and iatas:
var nonexistentIatas = iatas.filter(x => !result.includes(x));
The content of nonExistentIatas will be:
[
"BFS"
]

MongoDB find all not in this array

I'm trying to find all users except for a few, like this:
// get special user IDs
var special = db.special.find({}, { _id: 1 }).toArray();
// get all users except for the special ones
var users = db.users.find({_id: {$nin: special}});
This doesn't work because the array that I'm passing to $nin is not and array of ObjectId but an array of { _id: ObjectId() }
Variable special looks like this after the first query:
[ { _id: ObjectId(###) }, { _id: ObjectId(###) } ]
But $nin in the second query needs this:
[ ObjectId(###), ObjectId(###) ]
How can I get just the ObjectId() in an array from the first query so that I can use them in the second query?
Or, is there a better way of achieving what I'm trying to do?
Use the cursor.map() method returned by the find() function to transform the list of { _id: ObjectId(###) } documents to an array of ObjectId's as in the following
var special = db.special.find({}, { _id: 1 }).map(function(doc){
return doc._id;
});
Another approach you can consider is using the $lookup operator in the aggregation framework to do a "left outer join" on the special collection and filtering the documents on the new "joined" array field. The filter should match on documents whose array field is empty.
The following example demonstrates this:
db.users.aggregate([
{
"$lookup": {
"from": "special",
"localField": "_id",
"foreignField": "_id",
"as": "specialUsers" // <-- this will produce an arry of "joined" docs
}
},
{ "$match": { "specialUsers.0": { "$exists": false } } } // <-- match on empty array
])

ruby sorting hashes inside array

I have an array of hashes that I would like to sort based on the :reference values. But some of the elements within the array do not have a :reference key and therefore cannot be sorted. Is there a way to ignore this field and just sort the hash elements that contain this key?
I've tried the following approach but I'm getting an argument error
ArgumentError: comparison of NilClass with String failed
sort_by at org/jruby/RubyEnumerable.java:503
arr1 = [{:reference=> "F123",
:name=> "test4"
},
{
:reference=> "ZA4",
:name=> "test3"
},
{
:reference=> "A43",
:name=> "test2"
},
{
:name=> "test1"
},
{
:name=> "homework1"
}]
arr1 = arr1.sort_by { |hash| hash[:reference] }
puts arr1
The correct output should look like this :
=> arr1= [
{:reference=>"A43", :name=>"test2"},
{:reference=>"F123", :name=>"test4"},
{:reference=>"ZA4", :name=>"test3"},
{:name=> "test1"},
{:name=> "homework1"}
]
You can only sort on values that can be compared, so if you've got values of different types it's best to convert them to the same type first. A simple work-around is to convert to string:
arr1.sort_by { |hash| hash[:reference].to_s }
You can also assign a default:
arr1.sort_by { |hash| hash[:reference] || '' }
Edit: If you want the nil values sorted last:
arr1.sort_by { |hash| [ hash[:reference] ? 0 : 1, hash[:reference].to_s ] }
If you don't mind temporary variables, you could split the array into two arrays, one containing hashes with :reference and the other those without:
with_ref, without_ref = arr1.partition { |h| h[:reference] }
Then sort the first one:
with_ref.sort_by! { |h| h[:reference] }
And finally concatenate both arrays:
arr1 = with_ref + without_ref

MongoDB remove an item from an array inside an array of objects

I have a document that looks like this:
{
"_id" : ObjectId("56fea43a571332cc97e06d9c"),
"sections" : [
{
"_id" : ObjectId("56fea43a571332cc97e06d9e"),
"registered" : [
"123",
"e3d65a4e-2552-4995-ac5a-3c5180258d87"
]
}
]
}
I'd like to remove the 'e3d65a4e-2552-4995-ac5a-3c5180258d87' in the registered array of only the specific section with the _id of '56fea43a571332cc97e06d9e'.
My current attempt is something like this, but it just returns the original document unmodified.
db.test.findOneAndUpdate(
{
$and: [
{'sections._id': ObjectId('56fea43a571332cc97e06d9e')},
{'sections.registered': 'e3d65a4e-2552-4995-ac5a-3c5180258d87'}
]
},
{
$pull: {
$and: [
{'sections._id': ObjectId('56fea43a571332cc97e06d9e')},
{'sections.registered': 'e3d65a4e-2552-4995-ac5a-3c5180258d87'}
]
}
})
I've looked in to $pull, but I can't seem to figure out how to make it work on an array of nested objects containing another array. The $pull examples all seem to deal with only one level of nesting. How do I remove the matching entry from the registered array of the item in the sections array with the _id that I supply?
You need to use the positional $ update operator to remove the element from your array. You need this is because "sections" is an array of sub-documents.
db.test.findOneAndUpdate(
{ "sections._id" : ObjectId("56fea43a571332cc97e06d9e") },
{ "$pull": { "sections.$.registered": "e3d65a4e-2552-4995-ac5a-3c5180258d87" } }
)

Generate from two ruby arrays an appropriate JSON output

I have two simple ruby arrays and a JSON string mapping the elements of the first array to the elements of the second array:
keys = [:key0, :key1, :key2]
values = [:value0, :value1, :value2]
jsonString = {keys[0] => values[0], keys[1] => values[1], keys[2] => values[2]}
Writing this to a file:
file.write(JSON.pretty_generate(jsonString))
results into a nicely printed json object:
{
"key0": "value0",
"key1": "value1",
"key2": "value2"
}
But how can I generate the same output of two much bigger arrays without listing all these elements explicitly?
I just need something like
jsonString = {keys => values}
but this produces a different output:
{
"[:key0, :key1, :key2]":
[
"value0",
"value1",
"value2"
]
}
How can I map the two without looping over both?
array = keys.zip(values)
#=> [[:key0, :value0], [:key1, :value1], [:key2, :value2]]
Array#zip merges elements of self to the corresponding elements of the argument array and you get an array of arrays. This you can convert into a hash ...
hash = array.to_h
# => {:key0=>:value0, :key1=>:value1, :key2=>:value2}
... and the hash you can turn into a json string.
jsonString = JSON.pretty_generate(hash)
puts jsonString
#{
# "key0": "value0",
# "key1": "value1",
# "key2": "value2"
#}
Use Array#zip to make pairs of values and then make hash of them:
keys = [:key0, :key1, :key2]
values = [:value0, :value1, :value2]
Hash[keys.zip values]
# => {:key0=>:value0, :key1=>:value1, :key2=>:value2}

Resources