Let's say this is how my json looks like and it contains an array:
{
"status": {
"time": 175
},
"hits": [
{
"key1": "value1",
"key2": "value2"
},
{
"key1": "value1",
"key2": "value2"
},
{
"key1": "value1",
"key2": "value2"
},
]
}
I want to create an array of maps like this in react:
[
{mapkey1: value1, mapkey2: value2},
{mapkey1: value1, mapkey2: value2},
{mapkey1: value1, mapkey2: value2},
]
I already have a map of mapkeys to their xpaths in source json:
{
mapkey1: xpath1,
mapkey2: xpath2
}
How can I parse this map into another array using Lodash?
I know how to do it when there is no array:
_.mapValues(
xpathsMap,
paths => _.get(data, paths),
);
var arr = [
{
"key1": "value1",
"key2": "value2"
},
{
"key1": "value1",
"key2": "value2"
},
{
"key1": "value1",
"key2": "value2"
},
];
var output = [];
_.forEach(arr, function(obj) {
var keys = Object.keys(obj);
var ob = {};
_.forEach(keys, function(key) {
ob['map' + key] = obj[key];
})
output.push(ob);
});
console.log(output);
This will give you the desired output -
[
{mapkey1: "value1", mapkey2: "value2"},
{mapkey1: "value1", mapkey2: "value2"},
{mapkey1: "value1", mapkey2: "value2"}
]
Use Array#map to create a new array of objects. Create the object keys you require, using lodash's _.mapKeys():
const data = {"status":{"time":175},"hits":[{"key1":"value1","key2":"value2"},{"key1":"value1","key2":"value2"},{"key1":"value1","key2":"value2"}]}
const result = data.hits.map((o) => _.mapKeys(o, (val, key) => `map${key}`));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Related
I want to update many documents based on the condition in MongoDB.
MODEL is the collection which has the document with below information.
"info": [
{
"field1": "String1",
"field2": "String2"
},
{
"field1": "String1",
"field2": "String_2"
}
],
"var": "x"
I need to update all the "String1" value of field1 with "STRING_NEW". I used the below query to update but not working as expected.
db.model.updateMany(
{ "info.field1": { $exists: true } },
[
{ "$set": {
"info": {
"$map": {
"input": "$info.field1",
"in": {
"$cond": [
{ "$eq": ["$$this.field1", "String1"] },
"STRING_NEW",
$$this.field1
]
}
}
}
} }
]
)
Please have a look and suggest if anything is to be modified in the above query.
Solution 1
With the update with aggregation pipeline, you should iterate the object in info array and update the iterated object by merging the current object with new field1 field via $mergeObjects.
db.model.updateMany({
"info.field1": "String1"
},
[
{
"$set": {
"info": {
"$map": {
"input": "$info",
"in": {
"$cond": [
{
"$eq": [
"$$this.field1",
"String1"
]
},
{
$mergeObjects: [
"$$this",
{
"field1": "STRING_NEW"
}
]
},
"$$this"
]
}
}
}
}
}
])
Demo Solution 1 # Mongo Playground
Solution 2
Can also work with $[<identifier>] positional filtered operator and arrayFilters.
db.model.updateMany({
"info.field1": "String1"
},
{
"$set": {
"info.$[info].field1": "STRING_NEW"
}
},
{
arrayFilters: [
{
"info.field1": "String1"
}
]
})
Demo Solution 2 # Mongo Playground
I'm trying to figure out how to print just the attributes->preferences section in the following JSON example using jq. What's throwing me is that this is an array that contains multiple entries that are identified by an id key value pair and I need the attributes->preferences section just from the array element with id 1 without knowing the exact order of the array entries ahead of time.
[
{
"id": 1,
"attributes": {
"preferences": {
"key1": "value1",
"key2": "value2",
"key3": "value3",
"key4": "value4",
...
}
},
...
},
{
"id": 2,
...
},
{
"id": 4,
...
},
...
]
My desired output would be:
{
"key1": "value1",
"key2": "value2",
"key3": "value3",
"key4": "value4",
...
}
jq '.[] | select( .id == 1 ) | .attributes.preferences'
Demo on jqplay
I have the following query and it works with $in but not with $nin.
I'm trying to remove the link list items by name (itemA and itemB) from all records that are NOT part of a document that has a user name which contains '#not_these' or '#nor_these'.
db.users.update({userName:{$nin: [ RegExp('#not_these.com'), RegExp('#nor_these.com') ]}},{$pull:{'myLinkList': {name: {$in: ['itemA', 'itemB']} } } } )
If I make it $in and and declare the RegExp() explicitly it does remove the array items as expected.
db.users.update({userName:{$in: [ RegExp('#yes_these.com'), RegExp('#and_these.com') ]}},{$pull:{'myLinkList': {name: {$in: ['itemA', 'itemB']} } } } )
This one does remove itemA and itemB array list items for those explicitly declared users.
Why can't the items '#yes_these' and '#and_these' be removed using the first example? It seems to do nothing when executed.
Sample document:
{
"_id": ObjectId('5e34741aa18d8a0c24078b61'),
"myLinkList": [
{
"name": "item",
"created": ISODate('2020-01-31T18:38:18.682Z'),
"managedBy": [
"imm"
]
},
{
"name": "itemA",
"created": ISODate('2020-01-31T18:38:18.682Z'),
"managedBy": [
"imm"
]
},
{
"name": "itemB",
"created": ISODate('2020-01-31T18:38:18.682Z'),
"managedBy": [
"imm"
]
}
],
"userName": "#yes_these.com"
}
After update (hopefully):
{
"_id": ObjectId('5e34741aa18d8a0c24078b61'),
"myLinkList": [
{
"name": "item",
"created": ISODate('2020-01-31T18:38:18.682Z'),
"managedBy": [
"imm"
]
}
],
"userName": "#yes_these.com"
}
I verified this did work:
db.users.updateMany({userName:{$nin: [ /#not_these\.com/), /#nor_these\.com/) ]}},{$pull:{'myLinkList': {name: {$in: ['itemA', 'itemB']} } } } )
Given this
var applicationPayload =
[
"main": [
"key1": "value1",
"key2": [
"inside1": "insideValue1"
]
]
]
How can I append or add something inside key2 property.. I'd like the result to be something like this
[
"main": [
"key1": "value1",
"key2": [
"newInside2": "newInsideValue2",
"inside1": "insideValue1"
]
]
]
I tried doing this does not seems to work
applicationPayload["main"]["key2"]["newInside2"] = "newInsideValue2"
You could create a variable containing the current value of key2 and modify that before rewriting it back into the original dictionary:
import Foundation
var applicationPayload =
[
"main": [
"key1": "value1",
"key2": [
"inside1": "insideValue1"
]
]
]
print("Before: \(applicationPayload)")
var key2Value = applicationPayload["main"]?["key2"] as! [String: String]
key2Value["newInside2"] = "newInsideValue2"
applicationPayload["main"]?["key2"] = key2Value
print("After: \(applicationPayload)")
Output:
Before: ["main": ["key1": "value1", "key2": ["inside1": "insideValue1"]]]
After: ["main": ["key1": "value1", "key2": ["inside1": "insideValue1", "newInside2": "newInsideValue2"]]]
You can try for easy access/assign with keyPath
// get value of key2
var res = applicationPayload[keyPath:"main.key2"] as! [String:Any]
// add the other key
res["newInside2"] = "newInsideValue2"
// mutate key2
applicationPayload[keyPath:"main.key2"] = res
For more about keypaths check https://oleb.net/blog/2017/01/dictionary-key-paths/
Here is the data I'm getting from server. How do I store this JSON object in my backbone script and display it in a browser? Please help.
How can i built model or nested collection to retrive this data..
I am getting two kind of response from the server depend on query.
1st response:
[
{
"groups": [
{
"groupname": "Group_all",
"group": [
{
"displayname": "facebook",
"monitortype": "URL",
"responsetimereport": "value2",
"availabilityreport": "value4"
},
{
"displayname": "gmai",
"monitortype": "URL",
"responsetimereport": "value5",
"availabilityreport": "value6"
},
{
"displayname": "zoho",
"monitortype": "URL",
"responsetimereport": "value2",
"availabilityreport": "value1"
}
]
}
]
},
{
"monitor": []
}
]
2.Response
[
{
"groups": []
},
{
"monitor": [
{
"displayname": "facebook",
"monitortype": "URL",
"responsetimereport": "value2",
"availabilityreport": "value1"
}
]
}
]
what i have written to achieve this, i am pasting here
studentdb.Monitor = Backbone.Model.extend({
initialize : function(){
this.Displayname = this.get('displayname');
this.Monitortype = this.get('monitortype');
this.Responsetimereport = this.get('responsetimereport');
this.Availabilityreport= this.get('availabilityreport');
}
});
studentdb.Monitors = Backbone.Collection.extend({ model : studentdb.Monitor });
studentdb.Group1 = Backbone.Model.extend({
initialize : function(){
this.Displayname = this.get('displayname');
this.Monitortype = this.get('monitortype');
this.Responsetimereport = this.get('responsetimereport');
this.Availabilityreport= this.get('availabilityreport');
}
});
studentdb.Group1s = Backbone.Collection.extend({ model : studentdb.Group1 });
studentdb.Group_outer = Backbone.Model.extend({
defaults :{Groupname:""},
initialize : function(){
this.outer_group = new studentdb.Group1s(this.get('group'));
this.Groupname = this.get('groupname');
this.outer_group.parent = this;
}
});
studentdb.Group_outers = Backbone.Collection.extend({ model : studentdb.Group_outer });
studentdb.Overall = Backbone.Model.extend({
initialize : function(){
this.group_outer =new studentdb.Group_outers(this.get('groups'));
this.monitors = new studentdb.Monitors(this.get('monitor'));
}
});
studentdb.Final = Backbone.Collection.extend({
url:'https://data.json',
model : studentdb.Overall,
});
Basically, you must populate a collection with your data fetched from server, and then render your view based on a template.
Instead giving you a complete solution, i think you should first read some tutorials about backbone :
http://blog.joelberghoff.com/2012/07/22/backbone-js-tutorial-part-1/
http://backbonetutorials.com/what-is-a-collection/
could you post your collection code?
I'm afraid your json response probably can't be used directly in a backbone collection.
in that JSON, the array contains two members, the first one contains another array which has only one member (which contains groupName, and group( which really should be called groups))
if it is a 'Groups' collection, you will need to use parse.
docs here: http://backbonejs.org/#Collection-parse
it should process your response and return an array of Group model attributes like so:
[
{
"displayname": "facebook",
"monitortype": "URL",
"responsetimereport": "value2",
"availabilityreport": "value4"
},
{
"displayname": "gmai",
"monitortype": "URL",
"responsetimereport": "value5",
"availabilityreport": "value6"
},
{
"displayname": "zoho",
"monitortype": "URL",
"responsetimereport": "value2",
"availabilityreport": "value1"
}
]