I have a array of events and i want to make relation between these array's object.
array:
[{
'area': 'punjab',
'site': 'lahore',
'link': 'http: //lahore.com'
}, {
'area': 'punjab',
'site': 'sargodha',
'link': 'http: //sargodha.com'
}, {
'area': 'punjab',
'site': 'multan',
'link': 'http: //multan.com'
} {
'area': 'sindh',
'site': 'karachi',
'link': 'http: //karachi.com'
}]
Know i want to make the relation like
{
"area": "punjab",
"site": [
{
"name": "lahore",
"link": [
{
"name": "http://sargodha.com",
}
]
},
{
"name": "sargodha",
"link": [
{
"name": "http://sargodha.com",
}
]
}
]
},
{
"area": "sindh",
"site": [
{
"name": "karachi",
"link": [
{
"name": "http://karachi.com",
}
]
}
}
here is my code which i wrote:
function isinarrayfilters(matchingObject, targetArray, key) {
var existindex = -1;
$.each(targetArray, function(index, array) {
if (array.key == matchingObject.key) {
//Object exist in array
existindex = index;
}
});
return existindex;
}
generatedRelationArray = [];
$.each(alertsJson, function(index, alertJson) {
inarrayindex = isinarrayfilters(alertJson.area, relationArray,'area');
if (inarrayindex == -1) {
key = alertJson.site
generatedsites = {
"area": alertJson.area,
"site": []
}
relationArray.push(generatedsites);
}
});
Know anyone guide me how i append the site into the related area.
I have to run loop again and try to check the exist method and get the index and will push the sites into it?
A Format preserved answer:
var generate = function(list) {
var resultList = [];
var tmpStoreRef = {};
$.each(list, function(id, item) {
var area = item.area
,site = item.site
,link = item.link;
if (typeof tmpStoreRef[area] === 'undefined') {
tmpStoreRef[area] = {
area: area,
site: []
}
resultList.push(tmpStoreRef[area]);
}
tmpStoreRef[area].site.push({
name: site,
link: link
});
});
return resultList;
};
You can use query-js to accomplish this
Assuming your original array is stored in data
var res = data.groupBy(function(e){ return e.area; });
That would create a slightly different structure:
{
"punjab" : [{
'area': 'punjab',
'site': 'lahore',
'link': 'http: //lahore.com'
}, {
'area': 'punjab',
'site': 'sargodha',
'link': 'http: //sargodha.com'
}, {
'area': 'punjab',
'site': 'multan',
'link': 'http: //multan.com'
}],
"sindh": [...]
}
If you need that explicit structure then you can do this instead
var res = data.groupBy(function(e){ return e.area; })
.each(function(e){
return {
area : e.key,
site : e.value.select(function(e){
return {
name : e.site,
linkm : [e.link]
};
});
});
I've created a post that's supposed to be explanatory of what query-js is and how to use it
Related
I have this JSON generated from external (Reviews-io) script:
https://widget.reviews.co.uk/rich-snippet/dist.js
richSnippet({
store: "www.storedigital.local",
sku:"6647;6647_5;6647_4;6647_3;6647_11;6647_10;6647_2;6647_1;6647_9;6647_8;6647_7;6647_6",
data:{
"url": "store.stg.gsd.local/1/silla-replica-eames.html",
"description": ``,
"mpn": "6647",
"offers" :[{
"#type":"Offer",
"availability": "http://schema.org/InStock",
"price": "559",
"priceCurrency": "MXN",
"url": "https://store.stg.gsd.localx/1/silla-replica-eames.html",
"priceValidUntil": "2022-05-26",
}],
"brand": {
"#type": "Brand",
"name": "Not Available",
}
}
})
I need to get all the string of numbers in "sku", and then put them in another variable as same format (6647; 6647_1; 6647_2)
I try to get the numbers using this JS but doesn't works
var skucollection = JSON.parse(richSnippet, function (key, value) {
if (key == "sku") {
return new Sku(value);
} else {
return value;
}
});
Can you help me check what I am doing wrong, to get this sku's value string, please?
JSON.parse is not too much? ,handle it as it is internally (a JSON indeed)
var richSnippet = {
store: 'www.storedigital.local',
sku: '6647;6647_5;6647_4;6647_3;6647_11;6647_10;6647_2;6647_1;6647_9;6647_8;6647_7;6647_6',
algomas: [],
data: {
url: 'store.stg.gsd.local/1/silla-replica-eames.html',
description: ``,
mpn: '6647',
offers: [
{
'#type': 'Offer',
availability: 'http://schema.org/InStock',
price: '559',
priceCurrency: 'MXN',
url: 'https://store.stg.gsd.localx/1/silla-replica-eames.html',
priceValidUntil: '2022-05-26',
},
],
brand: {
'#type': 'Brand',
name: 'Not Available',
},
},
};
var test;
Object.keys(richSnippet).forEach((key) => {
if (key == 'sku') {
test = richSnippet[key];
}
});
console.log('test', test);
I've this array.
const routes = [
{
path:'/dashboard',
text: "Dashboard"
},
{
path:'/disputes',
text: "Disputes"
},
{
children: [
{
text: "Create Suburb",
path: "/create-suburb"
},
{
text: "View and Update Suburb",
path: "/view-suburb"
}
]
},
{
children: [
{
text: "Create user",
path: "/create-user"
},
{
text: "View and Update users",
path: "/view-users"
}
]
}
]
and I've this array
const permissions = ['/dashboard','/view-suburb'];
What I want is filter out objects from the array where there is not in the permissions array.
My expected out put is this
const routes = [
{
path:'/dashboard',
text: "Dashboard"
},
{
children: [
{
text: "View and Update Suburb",
path: "/view-suburb"
}
]
},
]
Note that two objects are completely removed and some part of the third object also removed. How do I achieve this using JS?
What I've done upto now is this
items.filter(e=>{
if(e.path){
return permissions.includes(e.path)
}else{
}
})
Hope my question is clear to you.
You could do it with a reduce - filter alone won't work here as you're actually transforming child arrays rather than purely filtering the top level array items
routes.reduce((result, route) => {
const { path, children } = route;
if (children) {
const filteredChildren = children.filter(child => permissions.includes(child.path));
// case where some child routes match permissions
if (filteredChildren.length !== 0) {
return [ ...result, { ...route, children: filteredChildren }];
}
}
// case where path is present and permissions includes path
if (path && permissions.includes(path)) {
return [ ...result, route ];
}
// case where there's no match between path and permissions
return result;
}, []);
Try this!!
const routes = [
{
path:'/dashboard',
text: "Dashboard"
},
{
path:'/disputes',
text: "Disputes"
},
{
children: [
{
text: "Create Suburb",
path: "/create-suburb"
},
{
text: "View and Update Suburb",
path: "/view-suburb"
}
]
},
{
children: [
{
text: "Create user",
path: "/create-user"
},
{
text: "View and Update users",
path: "/view-users"
}
]
}
]
const permissions = ['/dashboard','/view-suburb'];
let result = [];
permissions.map(permission=>{
routes.map(route=>{
if(route.hasOwnProperty('children')){
route.children.map((r,i)=>{
if(r.path == permission){
route.children = route.children.splice(i);
route.children = route.children.slice(-1);
result.push(route)
}
});
}else{
if(route.path == permission){
result.push(route)
}
}
});
})
console.log(result)
This one also worked for me.
var newData = [];
$.each(routes, function (key, value) {
debugger
var data = this;
if (data.path) {
if (permissions.includes(data.path)) {
newData.push(data);
}
}
else {
var data2 = data;
$.each(data2, function (key, value1) {
$.each(value1, function (key, value) {
var data = value;
if (data.path) {
if (permissions.includes(data.path)) {
newData.push(data);
}
}
});
});
}
})
Ideally, you should check the access to the route inside the canActivate guard and navigate the user further to the appropriate route.
I need to change my schema
const dataSchema = new Schema({
trackingPrice: [{
timeCheck: { type: Date, default: Date.now },
lowestPrice: Number,
salePrice: Number,
saleRank: Number
}]
})
to this
const dataSchema = new Schema({
trackingPrice: [{
timeCheck: { type: Date, default: Date.now },
lowestPrice: Number,
salePrice: Number
}],
trackingRank: [{
timeCheck: { type: Date, default: Date.now },
saleRank: Number
}]
})
How can I transfer my data from one to another under document and then delete "saleRank"?
Based on this very good answer, the cursor in your case would be derived from running the aggregate pipeline:
const pipeline = [
{
"$project": {
"trackingPrice": {
"$map": {
"input": "$trackingPrice",
"as": "el",
"in": {
"timeCheck": "$$el.timeCheck",
"lowestPrice": "$$el.timeCheck",
"salePrice": "$$el.salePrice"
}
}
},
"trackingRank": {
"$map": {
"input": "$trackingPrice",
"as": "el",
"in": {
"timeCheck": "$$el.timeCheck",
"saleRank": "$$el.saleRank"
}
}
}
}
}
];
const cursor = Data.aggregate(pipeline).exec();
Running the bulk update:
let bulkUpdateOps = [];
cursor.then(results => {
results.forEach(doc => {
const { _id, trackingPrice, trackingRank } = doc;
bulkUpdateOps.push({
"updateOne": {
"filter": { _id },
"update": { "$set": { trackingPrice, trackingRank } },
"upsert": true
}
});
});
if (bulkUpdateOps.length === 1000) {
bulkUpdateOps = [];
return Data.bulkWrite(bulkUpdateOps);
}
}).then(console.log).catch(console.error);
if (bulkUpdateOps.length > 0) {
Data.bulkWrite(bulkUpdateOps).then(console.log).catch(console.error);
}
The best way I see is to find all of them, and foreach one create a new one
I'm using mongoose by the way
dataSchema.find({}, (err,all) => {
var array = [];
all.foreach( (ds) => {
array.push({
trackingPrice: ds.trackingPrice,
trackingRank: //whatever way you want to update the old data
})
dataSchema.remove({}).exec(() => {
array.foreach((a) => {
var toadd = new dataSchema({
trackingPrice:a.trackingPrice,
trackingRank:a.trackingRank});
toadd.save();
})
})
})}
);
Hello all I have a question.
With this code:
targetingIdeaService.get({selector: selector}, function (error, result) {
var string = JSON.stringify(result)
console.log(string)
})
I get this result:
"totalNumEntries":700,
"entries":[
{
"data":[
{
"key":"KEYWORD_TEXT",
"value":{
"attributes":{
"xsi:type":"StringAttribute"
},
"Attribute.Type":"StringAttribute",
"value":"nike ddd8ea95"
}
},
{
"key":"COMPETITION",
"value":{
"attributes":{
"xsi:type":"DoubleAttribute"
},
"Attribute.Type":" DoubleAttribute",
"value":"0.8726547440705715"
}
},
{
"key":"AVERAGE_CPC",
"value":{
"attributes":{
"xsi:type":"MoneyAttribute"
},
"Attribute.Type":"MoneyAttribute",
"value":{
"ComparableValue.Type":"Money",
"microAmount":"16769286"
}
}
},
{
"key":"SEARCH_VOLUME",
"value":{
"attributes":{
"x si:type":"LongAttribute"
},
"Attribute.Type":"LongAttribute",
"value":"5609289"
}
}
]
}
]
}
And with this one i get the following:
targetingIdeaService.get({selector: selector}, function (error, result) {
var resultaten = result;
var res = resultaten.entries;
for(var i = 0; i < res.length; i++){
console.log(resultaten.entries[i])
}
})
Output
{ data:
[ { key: 'KEYWORD_TEXT', value: [Object] },
{ key: 'COMPETITION', value: [Object] },
{ key: 'AVERAGE_CPC', value: [Object] },
{ key: 'SEARCH_VOLUME', value: [Object] } ] }
Now im looking to format the JSON a certain way, It has to look like this example.
Notice: the key value pairs of json data.
[
{
"KEYWORD_TEXT": "red herring 9e23f4ad",
"SEARCH_VOLUME": 4574730
},
{
"KEYWORD_TEXT": "nike 656e95f0",
"SEARCH_VOLUME": 3442386
},
etc...
]
Basically the Key and the value of that key next to eachother. How to do this?
You can map the keys to values like following -
resultaten = result.data.map(function (item) {
return {
[item.key]: item.value
}
});
JSON.stringify(resultaten);
I'm building an app with Appcelerator.
I use Backbone to get data from database.
So I have build this code to get data from database:
var collection = Alloy.createCollection("SocialHistoryDAO");
collection.fetch();
Now I want to apply a where at this collection. So I use this code:
collection.where(id : 5);
Then this code works, but now I want to apply this filter:
"WHERE ID != 5";
It is possible to do this?
EDIT:
this is my SocialHistoryDAO model:
exports.definition = {
config: {
columns: {
"ID": "INTEGER PRIMARY KEY AUTOINCREMENT",
"IdOmnia": "INTEGER",
"DateStart": "text",
"DateEnd": "text",
"Quantity": "decimal",
"Code": "text",
"CodeSystem": "text",
"DisplayName": "text",
"DisplayNameTarget": "text",
"UnityMeasure": "text",
"StateID": "INTEGER"
},
adapter: {
type: "sql",
collection_name: "SocialHistoryDAO",
idAttribute: "ID"
}
},
extendModel: function(Model) {
_.extend(Model.prototype, {
// extended functions and properties go here
});
return Model;
},
extendCollection: function(Collection) {
_.extend(Collection.prototype, {
destroyAll : function(opt) {
var db = Ti.Database.open(this.config.adapter.db_name);
db.execute("DELETE FROM " + this.config.adapter.collection_name);
db.close();
this.models = [];
if (!opt || !opt.silent) { this.trigger("reset"); }
return this;
}
});
return Collection;
}
};
If you're using Backbone, then you're also using Underscore (or LoDash).
This can be accomplished using either:
var newArray = _.filter(collection.models, function(model) { return model.get('ID') != 5; });
or
var newArray = _.reject(collection.models, function(model) { return model.get('ID') == 5; });